JSONImporter.swift 37 KB

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