BolusStatsSetup.swift 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. import CoreData
  2. import Foundation
  3. /// Represents statistical data about bolus insulin for a specific time period
  4. struct BolusStats: Identifiable {
  5. let id = UUID()
  6. /// The date representing this time period
  7. let date: Date
  8. /// Total manual bolus insulin in units
  9. let manualBolus: Double
  10. /// Total SMB insulin in units
  11. let smb: Double
  12. /// Total external bolus insulin in units
  13. let external: Double
  14. }
  15. extension Stat.StateModel {
  16. /// Sets up bolus statistics by fetching and processing bolus data
  17. ///
  18. /// This function:
  19. /// 1. Fetches hourly and daily bolus statistics asynchronously
  20. /// 2. Updates the state model with the fetched statistics on the main actor
  21. /// 3. Calculates and caches initial daily averages
  22. func setupBolusStats() {
  23. Task {
  24. let (hourly, daily) = await fetchBolusStats()
  25. await MainActor.run {
  26. self.hourlyBolusStats = hourly
  27. self.dailyBolusStats = daily
  28. }
  29. // Initially calculate and cache daily averages
  30. await calculateAndCacheBolusAverages()
  31. }
  32. }
  33. /// Fetches and processes bolus statistics from Core Data
  34. /// - Returns: A tuple containing hourly and daily bolus statistics arrays
  35. ///
  36. /// This function:
  37. /// 1. Fetches bolus entries from Core Data
  38. /// 2. Groups entries by hour and day
  39. /// 3. Calculates total insulin for each time period
  40. /// 4. Returns the processed statistics as (hourly: [BolusStats], daily: [BolusStats])
  41. private func fetchBolusStats() async -> (hourly: [BolusStats], daily: [BolusStats]) {
  42. // Fetch PumpEventStored entries from Core Data
  43. let results = await CoreDataStack.shared.fetchEntitiesAsync(
  44. ofType: BolusStored.self,
  45. onContext: bolusTaskContext,
  46. predicate: NSPredicate.pumpHistoryForStats,
  47. key: "pumpEvent.timestamp",
  48. ascending: true,
  49. batchSize: 100
  50. )
  51. // Variables to hold the results
  52. var hourlyStats: [BolusStats] = []
  53. var dailyStats: [BolusStats] = []
  54. // Process CoreData results within the context's thread
  55. await bolusTaskContext.perform {
  56. guard let fetchedResults = results as? [BolusStored] else {
  57. return
  58. }
  59. let calendar = Calendar.current
  60. // Group entries by hour for hourly statistics
  61. let hourlyGrouped = Dictionary(grouping: fetchedResults) { entry in
  62. let components = calendar.dateComponents(
  63. [.year, .month, .day, .hour],
  64. from: entry.pumpEvent?.timestamp ?? Date()
  65. )
  66. return calendar.date(from: components) ?? Date()
  67. }
  68. // Group entries by day for daily statistics
  69. let dailyGrouped = Dictionary(grouping: fetchedResults) { entry in
  70. calendar.startOfDay(for: entry.pumpEvent?.timestamp ?? Date())
  71. }
  72. // Process hourly stats
  73. hourlyStats = hourlyGrouped.keys.sorted().map { timePoint in
  74. let entries = hourlyGrouped[timePoint, default: []]
  75. return BolusStats(
  76. date: timePoint,
  77. manualBolus: entries.reduce(0.0) { sum, entry in
  78. if !entry.isSMB, !entry.isExternal {
  79. return sum + (entry.amount?.doubleValue ?? 0)
  80. }
  81. return sum
  82. },
  83. smb: entries.reduce(0.0) { sum, entry in
  84. if entry.isSMB {
  85. return sum + (entry.amount?.doubleValue ?? 0)
  86. }
  87. return sum
  88. },
  89. external: entries.reduce(0.0) { sum, entry in
  90. if entry.isExternal {
  91. return sum + (entry.amount?.doubleValue ?? 0)
  92. }
  93. return sum
  94. }
  95. )
  96. }
  97. // Process daily stats
  98. dailyStats = dailyGrouped.keys.sorted().map { timePoint in
  99. let entries = dailyGrouped[timePoint, default: []]
  100. return BolusStats(
  101. date: timePoint,
  102. manualBolus: entries.reduce(0.0) { sum, entry in
  103. if !entry.isSMB, !entry.isExternal {
  104. return sum + (entry.amount?.doubleValue ?? 0)
  105. }
  106. return sum
  107. },
  108. smb: entries.reduce(0.0) { sum, entry in
  109. if entry.isSMB {
  110. return sum + (entry.amount?.doubleValue ?? 0)
  111. }
  112. return sum
  113. },
  114. external: entries.reduce(0.0) { sum, entry in
  115. if entry.isExternal {
  116. return sum + (entry.amount?.doubleValue ?? 0)
  117. }
  118. return sum
  119. }
  120. )
  121. }
  122. }
  123. return (hourlyStats, dailyStats)
  124. }
  125. /// Calculates and caches the daily averages of bolus insulin
  126. ///
  127. /// This function:
  128. /// 1. Groups bolus statistics by day
  129. /// 2. Calculates average total, carb and correction bolus for each day
  130. /// 3. Caches the results for later use
  131. ///
  132. /// This only needs to be called once during subscribe.
  133. private func calculateAndCacheBolusAverages() async {
  134. let calendar = Calendar.current
  135. // Calculate averages in context
  136. let dailyAverages = await bolusTaskContext.perform { [dailyBolusStats] in
  137. // Group by days
  138. let groupedByDay = Dictionary(grouping: dailyBolusStats) { stat in
  139. calendar.startOfDay(for: stat.date)
  140. }
  141. // Calculate averages for each day
  142. var averages: [Date: (Double, Double, Double)] = [:]
  143. for (day, stats) in groupedByDay {
  144. let total = stats.reduce((0.0, 0.0, 0.0)) { acc, stat in
  145. (acc.0 + stat.manualBolus, acc.1 + stat.smb, acc.2 + stat.external)
  146. }
  147. let count = Double(stats.count)
  148. averages[day] = (total.0 / count, total.1 / count, total.2 / count)
  149. }
  150. return averages
  151. }
  152. // Update cache on main thread
  153. await MainActor.run {
  154. self.bolusAveragesCache = dailyAverages
  155. }
  156. }
  157. /// Returns the average bolus values for the given date range from the cache
  158. /// - Parameter range: A tuple containing the start and end dates to get averages for
  159. /// - Returns: A tuple containing the average total, carb and correction bolus values for the date range
  160. func getCachedBolusAverages(for range: (start: Date, end: Date)) -> (manual: Double, smb: Double, external: Double) {
  161. return calculateBolusAveragesForDateRange(from: range.start, to: range.end)
  162. }
  163. /// Calculates the average bolus values for a given date range
  164. /// - Parameters:
  165. /// - startDate: The start date of the range to calculate averages for
  166. /// - endDate: The end date of the range to calculate averages for
  167. /// - Returns: A tuple containing the average total, carb and correction bolus values for the date range
  168. func calculateBolusAveragesForDateRange(
  169. from startDate: Date,
  170. to endDate: Date
  171. ) -> (manual: Double, smb: Double, external: Double) {
  172. // Filter cached values to only include those within the date range
  173. let relevantStats = bolusAveragesCache.filter { date, _ in
  174. date >= startDate && date <= endDate
  175. }
  176. // Return zeros if no data exists for the range
  177. guard !relevantStats.isEmpty else { return (0, 0, 0) }
  178. // Calculate total bolus across all days
  179. let total = relevantStats.values.reduce((0.0, 0.0, 0.0)) { acc, avg in
  180. (acc.0 + avg.0, acc.1 + avg.1, acc.2 + avg.2)
  181. }
  182. // Calculate averages by dividing totals by number of days
  183. let count = Double(relevantStats.count)
  184. return (total.0 / count, total.1 / count, total.2 / count)
  185. }
  186. }
  187. /// Extension to convert Decimal to Double
  188. private extension Decimal {
  189. var doubleValue: Double {
  190. NSDecimalNumber(decimal: self).doubleValue
  191. }
  192. }