JSONImporter.swift 38 KB

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