BolusStatsSetup.swift 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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 now = Date()
  62. let twentyDaysAgo = Calendar.current.date(byAdding: .day, value: -10, to: now) ?? now
  63. let hourlyGrouped = Dictionary(grouping: fetchedResults.filter { entry in
  64. guard let date = entry.pumpEvent?.timestamp else { return false }
  65. return date >= twentyDaysAgo && date <= now
  66. }) { entry in
  67. let components = calendar.dateComponents(
  68. [.year, .month, .day, .hour],
  69. from: entry.pumpEvent?.timestamp ?? Date()
  70. )
  71. return calendar.date(from: components) ?? Date()
  72. }
  73. // Group entries by day for daily statistics
  74. let dailyGrouped = Dictionary(grouping: fetchedResults) { entry in
  75. calendar.startOfDay(for: entry.pumpEvent?.timestamp ?? Date())
  76. }
  77. // Process hourly stats
  78. hourlyStats = hourlyGrouped.keys.sorted().map { timePoint in
  79. let entries = hourlyGrouped[timePoint, default: []]
  80. return BolusStats(
  81. date: timePoint,
  82. manualBolus: entries.reduce(0.0) { sum, entry in
  83. if !entry.isSMB, !entry.isExternal {
  84. return sum + (entry.amount?.doubleValue ?? 0)
  85. }
  86. return sum
  87. },
  88. smb: entries.reduce(0.0) { sum, entry in
  89. if entry.isSMB {
  90. return sum + (entry.amount?.doubleValue ?? 0)
  91. }
  92. return sum
  93. },
  94. external: entries.reduce(0.0) { sum, entry in
  95. if entry.isExternal {
  96. return sum + (entry.amount?.doubleValue ?? 0)
  97. }
  98. return sum
  99. }
  100. )
  101. }
  102. // Process daily stats
  103. dailyStats = dailyGrouped.keys.sorted().map { timePoint in
  104. let entries = dailyGrouped[timePoint, default: []]
  105. return BolusStats(
  106. date: timePoint,
  107. manualBolus: entries.reduce(0.0) { sum, entry in
  108. if !entry.isSMB, !entry.isExternal {
  109. return sum + (entry.amount?.doubleValue ?? 0)
  110. }
  111. return sum
  112. },
  113. smb: entries.reduce(0.0) { sum, entry in
  114. if entry.isSMB {
  115. return sum + (entry.amount?.doubleValue ?? 0)
  116. }
  117. return sum
  118. },
  119. external: entries.reduce(0.0) { sum, entry in
  120. if entry.isExternal {
  121. return sum + (entry.amount?.doubleValue ?? 0)
  122. }
  123. return sum
  124. }
  125. )
  126. }
  127. }
  128. return (hourlyStats, dailyStats)
  129. }
  130. /// Calculates and caches the daily averages of bolus insulin
  131. ///
  132. /// This function:
  133. /// 1. Groups bolus statistics by day
  134. /// 2. Calculates average total, carb and correction bolus for each day
  135. /// 3. Caches the results for later use
  136. ///
  137. /// This only needs to be called once during subscribe.
  138. private func calculateAndCacheBolusAverages() async {
  139. let calendar = Calendar.current
  140. // Calculate averages in context
  141. let dailyAverages = await bolusTaskContext.perform { [dailyBolusStats] in
  142. // Group by days
  143. let groupedByDay = Dictionary(grouping: dailyBolusStats) { stat in
  144. calendar.startOfDay(for: stat.date)
  145. }
  146. // Calculate averages for each day
  147. var averages: [Date: (Double, Double, Double)] = [:]
  148. for (day, stats) in groupedByDay {
  149. let total = stats.reduce((0.0, 0.0, 0.0)) { acc, stat in
  150. (acc.0 + stat.manualBolus, acc.1 + stat.smb, acc.2 + stat.external)
  151. }
  152. let count = Double(stats.count)
  153. averages[day] = (total.0 / count, total.1 / count, total.2 / count)
  154. }
  155. return averages
  156. }
  157. // Update cache on main thread
  158. await MainActor.run {
  159. self.bolusAveragesCache = dailyAverages
  160. }
  161. }
  162. /// Returns the average bolus values for the given date range from the cache
  163. /// - Parameter range: A tuple containing the start and end dates to get averages for
  164. /// - Returns: A tuple containing the average total, carb and correction bolus values for the date range
  165. func getCachedBolusAverages(for range: (start: Date, end: Date)) -> (manual: Double, smb: Double, external: Double) {
  166. return calculateBolusAveragesForDateRange(from: range.start, to: range.end)
  167. }
  168. /// Calculates the average bolus values for a given date range
  169. /// - Parameters:
  170. /// - startDate: The start date of the range to calculate averages for
  171. /// - endDate: The end date of the range to calculate averages for
  172. /// - Returns: A tuple containing the average total, carb and correction bolus values for the date range
  173. func calculateBolusAveragesForDateRange(
  174. from startDate: Date,
  175. to endDate: Date
  176. ) -> (manual: Double, smb: Double, external: Double) {
  177. // Filter cached values to only include those within the date range
  178. let relevantStats = bolusAveragesCache.filter { date, _ in
  179. date >= startDate && date <= endDate
  180. }
  181. // Return zeros if no data exists for the range
  182. guard !relevantStats.isEmpty else { return (0, 0, 0) }
  183. // Calculate total bolus across all days
  184. let total = relevantStats.values.reduce((0.0, 0.0, 0.0)) { acc, avg in
  185. (acc.0 + avg.0, acc.1 + avg.1, acc.2 + avg.2)
  186. }
  187. // Calculate averages by dividing totals by number of days
  188. let count = Double(relevantStats.count)
  189. return (total.0 / count, total.1 / count, total.2 / count)
  190. }
  191. }
  192. /// Extension to convert Decimal to Double
  193. private extension Decimal {
  194. var doubleValue: Double {
  195. NSDecimalNumber(decimal: self).doubleValue
  196. }
  197. }