JSONImporter.swift 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  1. import CoreData
  2. import Foundation
  3. /// Migration-specific errors that might happen during migration
  4. enum JSONImporterError: Error {
  5. case missingGlucoseValueInGlucoseEntry
  6. case tempBasalAndDurationMismatch
  7. case missingRequiredPropertyInPumpEntry
  8. case suspendResumePumpEventMismatch
  9. case duplicatePumpEvents
  10. case missingCarbsValueInCarbEntry
  11. case missingRequiredPropertyInDetermination
  12. }
  13. // MARK: - JSONImporter Class
  14. /// Responsible for importing JSON data into Core Data.
  15. ///
  16. /// The importer handles two important states:
  17. /// - JSON files stored in the file system that contain data to import
  18. /// - Existing entries in CoreData that should not be duplicated
  19. ///
  20. /// Imports are performed when a JSON file exists. The importer checks
  21. /// CoreData for existing entries to avoid duplicating records from partial imports.
  22. class JSONImporter {
  23. private let context: NSManagedObjectContext
  24. private let coreDataStack: CoreDataStack
  25. /// Initializes the importer with a Core Data context.
  26. init(context: NSManagedObjectContext, coreDataStack: CoreDataStack) {
  27. self.context = context
  28. self.coreDataStack = coreDataStack
  29. }
  30. /// Reads and parses a JSON file from the file system.
  31. ///
  32. /// - Parameters:
  33. /// - url: The URL of the JSON file to read.
  34. /// - Returns: A decoded object of the specified type.
  35. /// - Throws: An error if the file cannot be read or decoded.
  36. private func readJsonFile<T: Decodable>(url: URL) throws -> T {
  37. let data = try Data(contentsOf: url)
  38. let decoder = JSONCoding.decoder
  39. return try decoder.decode(T.self, from: data)
  40. }
  41. /// Retrieves the set of dates for all glucose values currently stored in CoreData.
  42. ///
  43. /// - Parameters: the start and end dates to fetch glucose values, inclusive
  44. /// - Returns: A set of dates corresponding to existing glucose readings.
  45. /// - Throws: An error if the fetch operation fails.
  46. private func fetchGlucoseDates(start: Date, end: Date) async throws -> Set<Date> {
  47. let allReadings = try await coreDataStack.fetchEntitiesAsync(
  48. ofType: GlucoseStored.self,
  49. onContext: context,
  50. predicate: .predicateForDateBetween(start: start, end: end),
  51. key: "date",
  52. ascending: false
  53. ) as? [GlucoseStored] ?? []
  54. return Set(allReadings.compactMap(\.date))
  55. }
  56. /// Retrieves the set of timestamps for all pump events currently stored in CoreData.
  57. ///
  58. /// - Parameters: the start and end dates to fetch pump events, inclusive
  59. /// - Returns: A set of dates corresponding to existing pump events.
  60. /// - Throws: An error if the fetch operation fails.
  61. private func fetchPumpTimestamps(start: Date, end: Date) async throws -> Set<Date> {
  62. let allPumpEvents = try await coreDataStack.fetchEntitiesAsync(
  63. ofType: PumpEventStored.self,
  64. onContext: context,
  65. predicate: .predicateForTimestampBetween(start: start, end: end),
  66. key: "timestamp",
  67. ascending: false
  68. ) as? [PumpEventStored] ?? []
  69. return Set(allPumpEvents.compactMap(\.timestamp))
  70. }
  71. /// Retrieves the set of timestamps for all carb entries currently stored in CoreData.
  72. ///
  73. /// - Parameters: the start and end dates to fetch carb entries, inclusive
  74. /// - Returns: A set of dates corresponding to existing carb entries.
  75. /// - Throws: An error if the fetch operation fails.
  76. private func fetchCarbEntryDates(start: Date, end: Date) async throws -> Set<Date> {
  77. let allCarbEntryDates = try await coreDataStack.fetchEntitiesAsync(
  78. ofType: CarbEntryStored.self,
  79. onContext: context,
  80. predicate: .predicateForDateBetween(start: start, end: end),
  81. key: "date",
  82. ascending: false
  83. ) as? [CarbEntryStored] ?? []
  84. return Set(allCarbEntryDates.compactMap(\.date))
  85. }
  86. /// Retrieves the set of dates for all oref determinations currently stored in CoreData.
  87. ///
  88. /// - Parameters:
  89. /// - start: the start to fetch from; inclusive
  90. /// - end: the end date to fetch to; inclusive
  91. /// - Returns: A set of dates corresponding to existing determinations.
  92. /// - Throws: An error if the fetch operation fails.
  93. private func fetchDeterminationDates(start: Date, end: Date) async throws -> Set<Date> {
  94. let determinations = try await coreDataStack.fetchEntitiesAsync(
  95. ofType: OrefDetermination.self,
  96. onContext: context,
  97. predicate: .predicateForDeliverAtBetween(start: start, end: end),
  98. key: "deliverAt",
  99. ascending: false
  100. ) as? [OrefDetermination] ?? []
  101. return Set(determinations.compactMap(\.deliverAt))
  102. }
  103. /// Imports glucose history from a JSON file into CoreData.
  104. ///
  105. /// The function reads glucose data from the provided JSON file and stores new entries
  106. /// in CoreData, skipping entries with dates that already exist in the database.
  107. ///
  108. /// - Parameters:
  109. /// - url: The URL of the JSON file containing glucose history.
  110. /// - now: The current time, used to skip old entries
  111. /// - Throws:
  112. /// - JSONImporterError.missingGlucoseValueInGlucoseEntry if a glucose entry is missing a value.
  113. /// - An error if the file cannot be read or decoded.
  114. /// - An error if the CoreData operation fails.
  115. func importGlucoseHistory(url: URL, now: Date) async throws {
  116. let twentyFourHoursAgo = now - 24.hours.timeInterval
  117. let glucoseHistoryFull: [BloodGlucose] = try readJsonFile(url: url)
  118. let existingDates = try await fetchGlucoseDates(start: twentyFourHoursAgo, end: now)
  119. // only import glucose values from the last 24 hours that don't exist
  120. let glucoseHistory = glucoseHistoryFull
  121. .filter { $0.dateString >= twentyFourHoursAgo && $0.dateString <= now && !existingDates.contains($0.dateString) }
  122. // Create a background context for batch processing
  123. let backgroundContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
  124. backgroundContext.parent = context
  125. try await backgroundContext.perform {
  126. for glucoseEntry in glucoseHistory {
  127. try glucoseEntry.store(in: backgroundContext)
  128. }
  129. try backgroundContext.save()
  130. }
  131. try await context.perform {
  132. try self.context.save()
  133. }
  134. }
  135. /// combines tempBasal and tempBasalDuration events into one PumpHistoryEvent
  136. private func combineTempBasalAndDuration(pumpHistory: [PumpHistoryEvent]) throws -> [PumpHistoryEvent] {
  137. let tempBasal = pumpHistory.filter({ $0.type == .tempBasal }).sorted { $0.timestamp < $1.timestamp }
  138. let tempBasalDuration = pumpHistory.filter({ $0.type == .tempBasalDuration }).sorted { $0.timestamp < $1.timestamp }
  139. let nonTempBasal = pumpHistory.filter { $0.type != .tempBasal && $0.type != .tempBasalDuration }
  140. guard tempBasal.count == tempBasalDuration.count else {
  141. throw JSONImporterError.tempBasalAndDurationMismatch
  142. }
  143. let combinedTempBasal = try zip(tempBasal, tempBasalDuration).map { rate, duration in
  144. guard rate.timestamp == duration.timestamp else {
  145. throw JSONImporterError.tempBasalAndDurationMismatch
  146. }
  147. return PumpHistoryEvent(
  148. id: duration.id,
  149. type: .tempBasal,
  150. timestamp: duration.timestamp,
  151. duration: duration.durationMin,
  152. rate: rate.rate,
  153. temp: rate.temp
  154. )
  155. }
  156. return (combinedTempBasal + nonTempBasal).sorted { $0.timestamp < $1.timestamp }
  157. }
  158. /// checks for pumpHistory inconsistencies that might cause issues if we import these events into CoreData
  159. private func checkForInconsistencies(pumpHistory: [PumpHistoryEvent]) throws {
  160. // make sure that pump suspends / resumes match up
  161. let suspendsAndResumes = pumpHistory.filter({ $0.type == .pumpSuspend || $0.type == .pumpResume })
  162. .sorted { $0.timestamp < $1.timestamp }
  163. for (current, next) in zip(suspendsAndResumes, suspendsAndResumes.dropFirst()) {
  164. guard current.type != next.type else {
  165. throw JSONImporterError.suspendResumePumpEventMismatch
  166. }
  167. }
  168. // check for duplicate events
  169. struct TypeTimestamp: Hashable {
  170. let timestamp: Date
  171. let type: EventType
  172. }
  173. let duplicates = Dictionary(grouping: pumpHistory) { TypeTimestamp(timestamp: $0.timestamp, type: $0.type) }
  174. .values.first(where: { $0.count > 1 })
  175. if duplicates != nil {
  176. throw JSONImporterError.duplicatePumpEvents
  177. }
  178. }
  179. /// Imports pump history from a JSON file into CoreData.
  180. ///
  181. /// The function reads pump history data from the provided JSON file and stores new entries
  182. /// in CoreData, skipping entries with timestamps that already exist in the database.
  183. ///
  184. /// - Parameters:
  185. /// - url: The URL of the JSON file containing pump history.
  186. /// - now: The current time, used to skip old entries
  187. /// - Throws:
  188. /// - JSONImporterError.tempBasalAndDurationMismatch if we can't match tempBasals with their duration.
  189. /// - An error if the file cannot be read or decoded.
  190. /// - An error if the CoreData operation fails.
  191. func importPumpHistory(url: URL, now: Date) async throws {
  192. let twentyFourHoursAgo = now - 24.hours.timeInterval
  193. let pumpHistoryRaw: [PumpHistoryEvent] = try readJsonFile(url: url)
  194. let existingTimestamps = try await fetchPumpTimestamps(start: twentyFourHoursAgo, end: now)
  195. let pumpHistoryFiltered = pumpHistoryRaw
  196. .filter { $0.timestamp >= twentyFourHoursAgo && $0.timestamp <= now && !existingTimestamps.contains($0.timestamp) }
  197. let pumpHistory = try combineTempBasalAndDuration(pumpHistory: pumpHistoryFiltered)
  198. try checkForInconsistencies(pumpHistory: pumpHistory)
  199. // Create a background context for batch processing
  200. let backgroundContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
  201. backgroundContext.parent = context
  202. try await backgroundContext.perform {
  203. for pumpEntry in pumpHistory {
  204. try pumpEntry.store(in: backgroundContext)
  205. }
  206. try backgroundContext.save()
  207. }
  208. try await context.perform {
  209. try self.context.save()
  210. }
  211. }
  212. /// Imports carb history from a JSON file into CoreData.
  213. ///
  214. /// The function reads carb entries data from the provided JSON file and stores new entries
  215. /// in CoreData, skipping entries with dates that already exist in the database.
  216. /// We ignore all FPU entries (aka carb equivalents) when performing an import.
  217. ///
  218. /// - Parameters:
  219. /// - url: The URL of the JSON file containing glucose history.
  220. /// - now: The current datetime
  221. /// - Throws:
  222. /// - JSONImporterError.missingCarbsValueInCarbEntry if a carb entry is missing a `carbs: Decimal` value.
  223. /// - An error if the file cannot be read or decoded.
  224. /// - An error if the CoreData operation fails.
  225. func importCarbHistory(url: URL, now: Date) async throws {
  226. let twentyFourHoursAgo = now - 24.hours.timeInterval
  227. let carbHistoryFull: [CarbsEntry] = try readJsonFile(url: url)
  228. let existingDates = try await fetchCarbEntryDates(start: twentyFourHoursAgo, end: now)
  229. // Only import carb entries from the last 24 hours that do not exist yet in Core Data
  230. // Only import "true" carb entries; ignore all FPU entries (aka carb equivalents)
  231. let carbHistory = carbHistoryFull
  232. .filter {
  233. let dateToCheck = $0.actualDate ?? $0.createdAt
  234. return dateToCheck >= twentyFourHoursAgo && dateToCheck <= now && !existingDates.contains(dateToCheck) && $0
  235. .isFPU ?? false == false }
  236. // Create a background context for batch processing
  237. let backgroundContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
  238. backgroundContext.parent = context
  239. try await backgroundContext.perform {
  240. for carbEntry in carbHistory {
  241. try carbEntry.store(in: backgroundContext)
  242. }
  243. try backgroundContext.save()
  244. }
  245. try await context.perform {
  246. try self.context.save()
  247. }
  248. }
  249. /// Imports oref determination from a JSON file into CoreData.
  250. ///
  251. /// The function reads oref determination data from the provided JSON file and stores new entries
  252. /// in CoreData, skipping entries with dates that already exist in the database.
  253. ///
  254. /// - Parameters:
  255. /// - url: The URL of the JSON file containing determination data.
  256. /// - Throws:
  257. /// - JSONImporterError.missingGlucoseValueInGlucoseEntry if a glucose entry is missing a value.
  258. /// - An error if the file cannot be read or decoded.
  259. /// - An error if the CoreData operation fails.
  260. func importOrefDetermination(enactedUrl: URL, suggestedUrl: URL, now: Date) async throws {
  261. let twentyFourHoursAgo = now - 24.hours.timeInterval
  262. let enactedDetermination: Determination = try readJsonFile(url: enactedUrl)
  263. let suggestedDetermination: Determination = try readJsonFile(url: suggestedUrl)
  264. let existingDates = try await fetchDeterminationDates(start: twentyFourHoursAgo, end: now)
  265. /// Helper function to check if entries are from within the last 24 hours that do not yet exist in Core Data
  266. func checkDeterminationDate(_ date: Date) -> Bool {
  267. date >= twentyFourHoursAgo && date <= now && !existingDates.contains(date)
  268. }
  269. guard let enactedDeliverAt = enactedDetermination.deliverAt,
  270. let suggestedDeliverAt = suggestedDetermination.deliverAt
  271. else {
  272. throw JSONImporterError.missingRequiredPropertyInDetermination
  273. }
  274. guard checkDeterminationDate(enactedDeliverAt), checkDeterminationDate(suggestedDeliverAt) else {
  275. return
  276. }
  277. // Create a background context for batch processing
  278. let backgroundContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
  279. backgroundContext.parent = context
  280. try await backgroundContext.perform {
  281. /// We know both determination entries are from within last 24 hrs via the check in line 140
  282. /// If their `deliverAt` does not match, it is worth storing them both
  283. if suggestedDeliverAt != enactedDeliverAt {
  284. try suggestedDetermination.store(in: backgroundContext)
  285. }
  286. try enactedDetermination.store(in: backgroundContext)
  287. try backgroundContext.save()
  288. }
  289. try await context.perform {
  290. try self.context.save()
  291. }
  292. }
  293. }
  294. // MARK: - Extension for Specific Import Functions
  295. extension BloodGlucose {
  296. /// Helper function to convert `BloodGlucose` to `GlucoseStored` while importing JSON glucose entries
  297. func store(in context: NSManagedObjectContext) throws {
  298. guard let glucoseValue = glucose ?? sgv else {
  299. throw JSONImporterError.missingGlucoseValueInGlucoseEntry
  300. }
  301. let glucoseEntry = GlucoseStored(context: context)
  302. glucoseEntry.id = _id.flatMap({ UUID(uuidString: $0) }) ?? UUID()
  303. glucoseEntry.date = dateString
  304. glucoseEntry.glucose = Int16(glucoseValue)
  305. glucoseEntry.direction = direction?.rawValue
  306. glucoseEntry.isManual = type == "Manual"
  307. glucoseEntry.isUploadedToNS = true
  308. glucoseEntry.isUploadedToHealth = true
  309. glucoseEntry.isUploadedToTidepool = true
  310. }
  311. }
  312. extension PumpHistoryEvent {
  313. /// Helper function to convert `PumpHistoryEvent` to `PumpEventStored` while importing JSON pump histories
  314. func store(in context: NSManagedObjectContext) throws {
  315. let pumpEntry = PumpEventStored(context: context)
  316. pumpEntry.id = id
  317. pumpEntry.timestamp = timestamp
  318. pumpEntry.type = type.rawValue
  319. pumpEntry.isUploadedToNS = true
  320. pumpEntry.isUploadedToHealth = true
  321. pumpEntry.isUploadedToTidepool = true
  322. if type == .bolus {
  323. guard let amount = amount else {
  324. throw JSONImporterError.missingRequiredPropertyInPumpEntry
  325. }
  326. let bolusEntry = BolusStored(context: context)
  327. bolusEntry.amount = NSDecimalNumber(decimal: amount)
  328. bolusEntry.isSMB = isSMB ?? false
  329. bolusEntry.isExternal = isExternal ?? false
  330. pumpEntry.bolus = bolusEntry
  331. } else if type == .tempBasal {
  332. guard let rate = rate, let duration = duration else {
  333. throw JSONImporterError.missingRequiredPropertyInPumpEntry
  334. }
  335. let tempEntry = TempBasalStored(context: context)
  336. tempEntry.rate = NSDecimalNumber(decimal: rate)
  337. tempEntry.duration = Int16(duration)
  338. tempEntry.tempType = temp?.rawValue
  339. pumpEntry.tempBasal = tempEntry
  340. }
  341. }
  342. }
  343. /// Extension to support decoding `CarbsEntry` from JSON with multiple possible key formats for entry notes.
  344. ///
  345. /// This is needed because some JSON sources (e.g., Trio v0.2.5) use the singular key `"note"`
  346. /// for the `note` field, while others (e.g., Nightscout or oref) use the plural `"notes"`.
  347. ///
  348. /// To ensure compatibility across all sources without duplicating models or requiring upstream fixes,
  349. /// this custom implementation attempts to decode the `note` field first from `"note"`, then from `"notes"`.
  350. /// Encoding will always use the canonical `"notes"` key to preserve consistency in output,
  351. /// as this is what's established throughout the backend now.
  352. extension CarbsEntry: Codable {
  353. init(from decoder: Decoder) throws {
  354. let container = try decoder.container(keyedBy: CodingKeys.self)
  355. id = try container.decodeIfPresent(String.self, forKey: .id)
  356. createdAt = try container.decode(Date.self, forKey: .createdAt)
  357. actualDate = try container.decodeIfPresent(Date.self, forKey: .actualDate)
  358. carbs = try container.decode(Decimal.self, forKey: .carbs)
  359. fat = try container.decodeIfPresent(Decimal.self, forKey: .fat)
  360. protein = try container.decodeIfPresent(Decimal.self, forKey: .protein)
  361. // Handle both `note` and `notes`
  362. if let noteValue = try? container.decodeIfPresent(String.self, forKey: .note) {
  363. note = noteValue
  364. } else if let notesValue = try? container.decodeIfPresent(String.self, forKey: .noteAlt) {
  365. note = notesValue
  366. } else {
  367. note = nil
  368. }
  369. enteredBy = try container.decodeIfPresent(String.self, forKey: .enteredBy)
  370. isFPU = try container.decodeIfPresent(Bool.self, forKey: .isFPU)
  371. fpuID = try container.decodeIfPresent(String.self, forKey: .fpuID)
  372. }
  373. func encode(to encoder: Encoder) throws {
  374. var container = encoder.container(keyedBy: CodingKeys.self)
  375. try container.encodeIfPresent(id, forKey: .id)
  376. try container.encode(createdAt, forKey: .createdAt)
  377. try container.encodeIfPresent(actualDate, forKey: .actualDate)
  378. try container.encode(carbs, forKey: .carbs)
  379. try container.encodeIfPresent(fat, forKey: .fat)
  380. try container.encodeIfPresent(protein, forKey: .protein)
  381. try container.encodeIfPresent(note, forKey: .note)
  382. try container.encodeIfPresent(enteredBy, forKey: .enteredBy)
  383. try container.encodeIfPresent(isFPU, forKey: .isFPU)
  384. try container.encodeIfPresent(fpuID, forKey: .fpuID)
  385. }
  386. private enum CodingKeys: String, CodingKey {
  387. case id = "_id"
  388. case createdAt = "created_at"
  389. case actualDate
  390. case carbs
  391. case fat
  392. case protein
  393. case note = "notes" // standard key
  394. case noteAlt = "note" // import key
  395. case enteredBy
  396. case isFPU
  397. case fpuID
  398. }
  399. /// Helper function to convert `CarbsStored` to `CarbEntryStored` while importing JSON carb entries
  400. func store(in context: NSManagedObjectContext) throws {
  401. guard carbs >= 0 else {
  402. throw JSONImporterError.missingCarbsValueInCarbEntry
  403. }
  404. // skip FPU entries for now
  405. let carbEntry = CarbEntryStored(context: context)
  406. carbEntry.id = id
  407. .flatMap({ UUID(uuidString: $0) }) ?? UUID() /// The `CodingKey` of `id` is `_id`, so this fine to use here
  408. carbEntry.date = actualDate ?? createdAt
  409. carbEntry.carbs = Double(truncating: NSDecimalNumber(decimal: carbs))
  410. carbEntry.fat = Double(truncating: NSDecimalNumber(decimal: fat ?? 0))
  411. carbEntry.protein = Double(truncating: NSDecimalNumber(decimal: protein ?? 0))
  412. carbEntry.note = note ?? ""
  413. carbEntry.isFPU = false
  414. carbEntry.isUploadedToNS = true
  415. carbEntry.isUploadedToHealth = true
  416. carbEntry.isUploadedToTidepool = true
  417. if fat != nil, protein != nil, let fpuId = fpuID {
  418. carbEntry.fpuID = UUID(uuidString: fpuId)
  419. }
  420. }
  421. }
  422. /// Extension to support decoding `Determination` entries with misspelled keys from external JSON sources.
  423. ///
  424. /// Some legacy or third-party tools occasionally serialize the `received` property as `"recieved"`
  425. /// (misspelled) instead of the correct `"received"`. To prevent decoding failures or data loss,
  426. /// this custom decoder attempts to decode from `"received"` first, then falls back to `"recieved"`
  427. /// if necessary.
  428. ///
  429. /// Encoding always uses the correct `"received"` key to ensure consistent, standards-compliant output.
  430. ///
  431. /// This improves resilience and ensures compatibility with imported loop history, simulations,
  432. /// or devicestatus artifacts that may contain typos in their keys.
  433. extension Determination: Codable {
  434. private enum CodingKeys: String, CodingKey {
  435. case id
  436. case reason
  437. case units
  438. case insulinReq
  439. case eventualBG
  440. case sensitivityRatio
  441. case rate
  442. case duration
  443. case iob = "IOB"
  444. case cob = "COB"
  445. case predictions = "predBGs"
  446. case deliverAt
  447. case carbsReq
  448. case temp
  449. case bg
  450. case reservoir
  451. case timestamp
  452. case isf = "ISF"
  453. case current_target
  454. case tdd = "TDD"
  455. case insulinForManualBolus
  456. case manualBolusErrorString
  457. case minDelta
  458. case expectedDelta
  459. case minGuardBG
  460. case minPredBG
  461. case threshold
  462. case carbRatio = "CR"
  463. case received
  464. case receivedAlt = "recieved"
  465. }
  466. init(from decoder: Decoder) throws {
  467. let container = try decoder.container(keyedBy: CodingKeys.self)
  468. id = try container.decodeIfPresent(UUID.self, forKey: .id)
  469. reason = try container.decode(String.self, forKey: .reason)
  470. units = try container.decodeIfPresent(Decimal.self, forKey: .units)
  471. insulinReq = try container.decodeIfPresent(Decimal.self, forKey: .insulinReq)
  472. eventualBG = try container.decodeIfPresent(Int.self, forKey: .eventualBG)
  473. sensitivityRatio = try container.decodeIfPresent(Decimal.self, forKey: .sensitivityRatio)
  474. rate = try container.decodeIfPresent(Decimal.self, forKey: .rate)
  475. duration = try container.decodeIfPresent(Decimal.self, forKey: .duration)
  476. iob = try container.decodeIfPresent(Decimal.self, forKey: .iob)
  477. cob = try container.decodeIfPresent(Decimal.self, forKey: .cob)
  478. predictions = try container.decodeIfPresent(Predictions.self, forKey: .predictions)
  479. deliverAt = try container.decodeIfPresent(Date.self, forKey: .deliverAt)
  480. carbsReq = try container.decodeIfPresent(Decimal.self, forKey: .carbsReq)
  481. temp = try container.decodeIfPresent(TempType.self, forKey: .temp)
  482. bg = try container.decodeIfPresent(Decimal.self, forKey: .bg)
  483. reservoir = try container.decodeIfPresent(Decimal.self, forKey: .reservoir)
  484. timestamp = try container.decodeIfPresent(Date.self, forKey: .timestamp)
  485. isf = try container.decodeIfPresent(Decimal.self, forKey: .isf)
  486. current_target = try container.decodeIfPresent(Decimal.self, forKey: .current_target)
  487. tdd = try container.decodeIfPresent(Decimal.self, forKey: .tdd)
  488. insulinForManualBolus = try container.decodeIfPresent(Decimal.self, forKey: .insulinForManualBolus)
  489. manualBolusErrorString = try container.decodeIfPresent(Decimal.self, forKey: .manualBolusErrorString)
  490. minDelta = try container.decodeIfPresent(Decimal.self, forKey: .minDelta)
  491. expectedDelta = try container.decodeIfPresent(Decimal.self, forKey: .expectedDelta)
  492. minGuardBG = try container.decodeIfPresent(Decimal.self, forKey: .minGuardBG)
  493. minPredBG = try container.decodeIfPresent(Decimal.self, forKey: .minPredBG)
  494. threshold = try container.decodeIfPresent(Decimal.self, forKey: .threshold)
  495. carbRatio = try container.decodeIfPresent(Decimal.self, forKey: .carbRatio)
  496. // Handle both spellings of "received"
  497. if let value = try container.decodeIfPresent(Bool.self, forKey: .received) {
  498. received = value
  499. } else if let fallback = try container.decodeIfPresent(Bool.self, forKey: .receivedAlt) {
  500. received = fallback
  501. } else {
  502. received = nil
  503. }
  504. }
  505. func encode(to encoder: Encoder) throws {
  506. var container = encoder.container(keyedBy: CodingKeys.self)
  507. try container.encodeIfPresent(id, forKey: .id)
  508. try container.encode(reason, forKey: .reason)
  509. try container.encodeIfPresent(units, forKey: .units)
  510. try container.encodeIfPresent(insulinReq, forKey: .insulinReq)
  511. try container.encodeIfPresent(eventualBG, forKey: .eventualBG)
  512. try container.encodeIfPresent(sensitivityRatio, forKey: .sensitivityRatio)
  513. try container.encodeIfPresent(rate, forKey: .rate)
  514. try container.encodeIfPresent(duration, forKey: .duration)
  515. try container.encodeIfPresent(iob, forKey: .iob)
  516. try container.encodeIfPresent(cob, forKey: .cob)
  517. try container.encodeIfPresent(predictions, forKey: .predictions)
  518. try container.encodeIfPresent(deliverAt, forKey: .deliverAt)
  519. try container.encodeIfPresent(carbsReq, forKey: .carbsReq)
  520. try container.encodeIfPresent(temp, forKey: .temp)
  521. try container.encodeIfPresent(bg, forKey: .bg)
  522. try container.encodeIfPresent(reservoir, forKey: .reservoir)
  523. try container.encodeIfPresent(timestamp, forKey: .timestamp)
  524. try container.encodeIfPresent(isf, forKey: .isf)
  525. try container.encodeIfPresent(current_target, forKey: .current_target)
  526. try container.encodeIfPresent(tdd, forKey: .tdd)
  527. try container.encodeIfPresent(insulinForManualBolus, forKey: .insulinForManualBolus)
  528. try container.encodeIfPresent(manualBolusErrorString, forKey: .manualBolusErrorString)
  529. try container.encodeIfPresent(minDelta, forKey: .minDelta)
  530. try container.encodeIfPresent(expectedDelta, forKey: .expectedDelta)
  531. try container.encodeIfPresent(minGuardBG, forKey: .minGuardBG)
  532. try container.encodeIfPresent(minPredBG, forKey: .minPredBG)
  533. try container.encodeIfPresent(threshold, forKey: .threshold)
  534. try container.encodeIfPresent(carbRatio, forKey: .carbRatio)
  535. try container.encodeIfPresent(received, forKey: .received) // always encode the correct spelling
  536. }
  537. /// Helper function to convert `Determination` to `OrefDetermination` while importing JSON glucose entries
  538. func store(in context: NSManagedObjectContext) throws {
  539. // TODO: some guards here ?!
  540. let newOrefDetermination = OrefDetermination(context: context)
  541. newOrefDetermination.id = UUID()
  542. newOrefDetermination.insulinSensitivity = decimalToNSDecimalNumber(isf)
  543. newOrefDetermination.currentTarget = decimalToNSDecimalNumber(current_target)
  544. newOrefDetermination.eventualBG = eventualBG.map(NSDecimalNumber.init)
  545. newOrefDetermination.deliverAt = deliverAt
  546. newOrefDetermination.timestamp = timestamp
  547. newOrefDetermination.enacted = received ?? false
  548. newOrefDetermination.insulinForManualBolus = decimalToNSDecimalNumber(insulinForManualBolus)
  549. newOrefDetermination.carbRatio = decimalToNSDecimalNumber(carbRatio)
  550. newOrefDetermination.glucose = decimalToNSDecimalNumber(bg)
  551. newOrefDetermination.reservoir = decimalToNSDecimalNumber(reservoir)
  552. newOrefDetermination.insulinReq = decimalToNSDecimalNumber(insulinReq)
  553. newOrefDetermination.temp = temp?.rawValue ?? "absolute"
  554. newOrefDetermination.rate = decimalToNSDecimalNumber(rate)
  555. newOrefDetermination.reason = reason
  556. newOrefDetermination.duration = decimalToNSDecimalNumber(duration)
  557. newOrefDetermination.iob = decimalToNSDecimalNumber(iob)
  558. newOrefDetermination.threshold = decimalToNSDecimalNumber(threshold)
  559. newOrefDetermination.minDelta = decimalToNSDecimalNumber(minDelta)
  560. newOrefDetermination.sensitivityRatio = decimalToNSDecimalNumber(sensitivityRatio)
  561. newOrefDetermination.expectedDelta = decimalToNSDecimalNumber(expectedDelta)
  562. newOrefDetermination.cob = Int16(Int(cob ?? 0))
  563. newOrefDetermination.manualBolusErrorString = decimalToNSDecimalNumber(manualBolusErrorString)
  564. newOrefDetermination.smbToDeliver = units.map { NSDecimalNumber(decimal: $0) }
  565. newOrefDetermination.carbsRequired = Int16(Int(carbsReq ?? 0))
  566. newOrefDetermination.isUploadedToNS = true
  567. if let predictions = predictions {
  568. ["iob": predictions.iob, "zt": predictions.zt, "cob": predictions.cob, "uam": predictions.uam]
  569. .forEach { type, values in
  570. if let values = values {
  571. let forecast = Forecast(context: context)
  572. forecast.id = UUID()
  573. forecast.type = type
  574. forecast.date = Date()
  575. forecast.orefDetermination = newOrefDetermination
  576. for (index, value) in values.enumerated() {
  577. let forecastValue = ForecastValue(context: context)
  578. forecastValue.index = Int32(index)
  579. forecastValue.value = Int32(value)
  580. forecast.addToForecastValues(forecastValue)
  581. }
  582. newOrefDetermination.addToForecasts(forecast)
  583. }
  584. }
  585. }
  586. }
  587. func decimalToNSDecimalNumber(_ value: Decimal?) -> NSDecimalNumber? {
  588. guard let value = value else { return nil }
  589. return NSDecimalNumber(decimal: value)
  590. }
  591. }
  592. extension JSONImporter {
  593. func importGlucoseHistoryIfNeeded() async {}
  594. func importPumpHistoryIfNeeded() async {}
  595. func importCarbHistoryIfNeeded() async {}
  596. func importDeterminationIfNeeded() async {}
  597. }