health: fix medical Health Connect sync accuracy
- Commit
d4c3bf4b5e24288f4507add47b0d06a71283b070- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-25 23:32 UTC (1 month ago)
- Parents
7018d18
Diff
health/src/main/java/com/vayunmathur/health/data/HealthRepository.kt
diff --git a/health/src/main/java/com/vayunmathur/health/data/HealthRepository.kt b/health/src/main/java/com/vayunmathur/health/data/HealthRepository.ktindex 28f082833e..875131d805 100644--- a/health/src/main/java/com/vayunmathur/health/data/HealthRepository.kt+++ b/health/src/main/java/com/vayunmathur/health/data/HealthRepository.kt@@ -101,18 +101,20 @@ class HealthRepository private constructor(context: Context) : // Medical history — vaccinations, medications and their attachments suspend fun upsertVaccination(entry: VaccinationEntry) = medicalDao.upsertVaccination(entry)- suspend fun upsertVaccinations(entries: List<VaccinationEntry>) = medicalDao.upsertVaccinations(entries) suspend fun deleteVaccination(entry: VaccinationEntry) = medicalDao.deleteVaccination(entry) fun getVaccinationsFlow(): Flow<List<VaccinationEntry>> = medicalDao.getVaccinationsFlow() suspend fun getVaccination(id: String): VaccinationEntry? = medicalDao.getVaccination(id)- suspend fun getMirroredVaccinations(): List<VaccinationEntry> = medicalDao.getMirroredVaccinations()+ suspend fun findVaccination(dataSourceId: String, fhirResourceId: String): VaccinationEntry? =+ medicalDao.findVaccination(dataSourceId, fhirResourceId) suspend fun upsertMedication(entry: MedicationEntry) = medicalDao.upsertMedication(entry)- suspend fun upsertMedications(entries: List<MedicationEntry>) = medicalDao.upsertMedications(entries) suspend fun deleteMedication(entry: MedicationEntry) = medicalDao.deleteMedication(entry) fun getMedicationsFlow(): Flow<List<MedicationEntry>> = medicalDao.getMedicationsFlow() suspend fun getMedication(id: String): MedicationEntry? = medicalDao.getMedication(id)- suspend fun getMirroredMedications(): List<MedicationEntry> = medicalDao.getMirroredMedications()+ suspend fun findMedication(dataSourceId: String, fhirResourceId: String): MedicationEntry? =+ medicalDao.findMedication(dataSourceId, fhirResourceId)+ suspend fun findMedicationsByFhirId(fhirResourceId: String): List<MedicationEntry> =+ medicalDao.findMedicationsByFhirId(fhirResourceId) suspend fun insertAttachment(attachment: MedicalAttachment) = medicalDao.insertAttachment(attachment) suspend fun deleteAttachment(attachment: MedicalAttachment) = medicalDao.deleteAttachment(attachment)@@ -131,23 +133,26 @@ class HealthRepository private constructor(context: Context) : // Allergies and conditions suspend fun upsertAllergy(entry: AllergyEntry) = medicalDao.upsertAllergy(entry)- suspend fun upsertAllergies(entries: List<AllergyEntry>) = medicalDao.upsertAllergies(entries) suspend fun deleteAllergy(entry: AllergyEntry) = medicalDao.deleteAllergy(entry) fun getAllergiesFlow(): Flow<List<AllergyEntry>> = medicalDao.getAllergiesFlow() suspend fun getAllergy(id: String): AllergyEntry? = medicalDao.getAllergy(id)+ suspend fun findAllergy(dataSourceId: String, fhirResourceId: String): AllergyEntry? =+ medicalDao.findAllergy(dataSourceId, fhirResourceId) suspend fun upsertCondition(entry: ConditionEntry) = medicalDao.upsertCondition(entry)- suspend fun upsertConditions(entries: List<ConditionEntry>) = medicalDao.upsertConditions(entries) suspend fun deleteCondition(entry: ConditionEntry) = medicalDao.deleteCondition(entry) fun getConditionsFlow(): Flow<List<ConditionEntry>> = medicalDao.getConditionsFlow() suspend fun getCondition(id: String): ConditionEntry? = medicalDao.getCondition(id)+ suspend fun findCondition(dataSourceId: String, fhirResourceId: String): ConditionEntry? =+ medicalDao.findCondition(dataSourceId, fhirResourceId) // Lab results and the standing profile suspend fun upsertLabResult(entry: LabResultEntry) = medicalDao.upsertLabResult(entry)- suspend fun upsertLabResults(entries: List<LabResultEntry>) = medicalDao.upsertLabResults(entries) suspend fun deleteLabResult(entry: LabResultEntry) = medicalDao.deleteLabResult(entry) fun getLabResultsFlow(): Flow<List<LabResultEntry>> = medicalDao.getLabResultsFlow() suspend fun getLabResult(id: String): LabResultEntry? = medicalDao.getLabResult(id)+ suspend fun findLabResult(dataSourceId: String, fhirResourceId: String): LabResultEntry? =+ medicalDao.findLabResult(dataSourceId, fhirResourceId) suspend fun upsertProfile(profile: HealthProfile) = medicalDao.upsertProfile(profile) fun getProfileFlow(): Flow<HealthProfile?> = medicalDao.getProfileFlow()@@ -161,13 +166,26 @@ class HealthRepository private constructor(context: Context) : // Doses taken suspend fun upsertDoseEvent(event: DoseEvent) = medicalDao.upsertDoseEvent(event)- suspend fun upsertDoseEvents(events: List<DoseEvent>) = medicalDao.upsertDoseEvents(events) suspend fun deleteDoseEvent(event: DoseEvent) = medicalDao.deleteDoseEvent(event) fun getDoseEventsFlow(): Flow<List<DoseEvent>> = medicalDao.getDoseEventsFlow() suspend fun getRecentDoses(medicationId: String, limit: Int): List<DoseEvent> = medicalDao.getRecentDoses(medicationId, limit) suspend fun getDoseEvent(id: String): DoseEvent? = medicalDao.getDoseEvent(id) suspend fun deleteDosesFor(medicationId: String) = medicalDao.deleteDosesFor(medicationId)+ suspend fun getDosesFor(medicationId: String): List<DoseEvent> = medicalDao.getDosesFor(medicationId)+ suspend fun findDoseEvent(dataSourceId: String, fhirResourceId: String): DoseEvent? =+ medicalDao.findDoseEvent(dataSourceId, fhirResourceId)++ // Health Connect bookkeeping+ suspend fun upsertTombstone(tombstone: DeletedMedicalResource) = medicalDao.upsertTombstone(tombstone)+ suspend fun isTombstoned(kind: MedicalKind, dataSourceId: String, fhirResourceId: String): Boolean =+ medicalDao.isTombstoned(kind, dataSourceId, fhirResourceId)+ suspend fun getPendingRemoteDeletes(dataSourceId: String): List<DeletedMedicalResource> =+ medicalDao.getPendingRemoteDeletes(dataSourceId)+ suspend fun markPending(kind: MedicalKind, rowId: String) =+ medicalDao.insertPendingMirror(PendingMirror(kind, rowId))+ suspend fun clearPending(kind: MedicalKind, rowId: String) = medicalDao.deletePendingMirror(kind, rowId)+ suspend fun getPendingMirrors(): List<PendingMirror> = medicalDao.getPendingMirrors() /** * Expose underlying [HealthDatabase] for call sites that need transactional access
health/src/main/java/com/vayunmathur/health/data/MedicalRecords.kt
diff --git a/health/src/main/java/com/vayunmathur/health/data/MedicalRecords.kt b/health/src/main/java/com/vayunmathur/health/data/MedicalRecords.ktindex c69c3658da..d464735f02 100644--- a/health/src/main/java/com/vayunmathur/health/data/MedicalRecords.kt+++ b/health/src/main/java/com/vayunmathur/health/data/MedicalRecords.kt@@ -36,12 +36,12 @@ data class VaccinationEntry( val dataSourceId: String? = null, ) -/** Whether a medication is still being taken. Maps to FHIR `MedicationStatement.status`. */+/** Whether a medication is still being taken. Maps to FHIR `MedicationRequest.status`. */ enum class MedicationStatus { Active, Completed, Stopped } /** * A medication the user takes or has taken, mirrored to Health Connect as a FHIR- * `MedicationStatement`. Same nullable-FHIR-columns arrangement as [VaccinationEntry].+ * `MedicationRequest`. Same nullable-FHIR-columns arrangement as [VaccinationEntry]. */ @Entity(indices = [Index(value = ["startedAt"])]) data class MedicationEntry(@@ -231,8 +231,30 @@ data class ConditionEntry( val dataSourceId: String? = null, ) +/** Which medical table a [DeletedMedicalResource] or [PendingMirror] refers to. */+enum class MedicalKind { Vaccination, Medication, Dose, Allergy, Condition, LabResult }++/**+ * A Health Connect resource the user deleted here, so the next import does not bring it back.+ *+ * Another app's records are read-only to this one, and deleting our own can fail or happen while+ * the feature is unavailable. [retryDelete] is true while our own copy still needs removing.+ */+@Entity(primaryKeys = ["kind", "dataSourceId", "fhirResourceId"])+data class DeletedMedicalResource(+ val kind: MedicalKind,+ val dataSourceId: String,+ val fhirResourceId: String,+ val fhirResourceType: Int,+ val retryDelete: Boolean,+)++/** A row whose latest local state has not reached Health Connect yet. */+@Entity(primaryKeys = ["kind", "rowId"])+data class PendingMirror(val kind: MedicalKind, val rowId: String)+ @Dao-// Query surface of the medical tables: one method per query by Room's design.+// Query surface of the medical tables // Splitting the interface would only move the same method count to more files. @Suppress("TooManyFunctions") interface MedicalDao {@@ -242,9 +264,6 @@ interface MedicalDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun upsertVaccination(entry: VaccinationEntry) - @Insert(onConflict = OnConflictStrategy.REPLACE)- suspend fun upsertVaccinations(entries: List<VaccinationEntry>)- @Update suspend fun updateVaccination(entry: VaccinationEntry) @@ -257,18 +276,17 @@ interface MedicalDao { @Query("SELECT * FROM VaccinationEntry WHERE id = :id") suspend fun getVaccination(id: String): VaccinationEntry? - /** Used to reconcile a Health Connect read against what is already stored locally. */- @Query("SELECT * FROM VaccinationEntry WHERE fhirResourceId IS NOT NULL")- suspend fun getMirroredVaccinations(): List<VaccinationEntry>+ @Query(+ "SELECT * FROM VaccinationEntry " ++ "WHERE dataSourceId = :dataSourceId AND fhirResourceId = :fhirResourceId LIMIT 1"+ )+ suspend fun findVaccination(dataSourceId: String, fhirResourceId: String): VaccinationEntry? // --- Medications ------------------------------------------------------- @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun upsertMedication(entry: MedicationEntry) - @Insert(onConflict = OnConflictStrategy.REPLACE)- suspend fun upsertMedications(entries: List<MedicationEntry>)- @Update suspend fun updateMedication(entry: MedicationEntry) @@ -281,8 +299,14 @@ interface MedicalDao { @Query("SELECT * FROM MedicationEntry WHERE id = :id") suspend fun getMedication(id: String): MedicationEntry? - @Query("SELECT * FROM MedicationEntry WHERE fhirResourceId IS NOT NULL")- suspend fun getMirroredMedications(): List<MedicationEntry>+ @Query(+ "SELECT * FROM MedicationEntry " ++ "WHERE dataSourceId = :dataSourceId AND fhirResourceId = :fhirResourceId LIMIT 1"+ )+ suspend fun findMedication(dataSourceId: String, fhirResourceId: String): MedicationEntry?++ @Query("SELECT * FROM MedicationEntry WHERE fhirResourceId = :fhirResourceId")+ suspend fun findMedicationsByFhirId(fhirResourceId: String): List<MedicationEntry> // --- Attachments ------------------------------------------------------- @@ -303,9 +327,6 @@ interface MedicalDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun upsertAllergy(entry: AllergyEntry) - @Insert(onConflict = OnConflictStrategy.REPLACE)- suspend fun upsertAllergies(entries: List<AllergyEntry>)- @Delete suspend fun deleteAllergy(entry: AllergyEntry) @@ -316,14 +337,17 @@ interface MedicalDao { @Query("SELECT * FROM AllergyEntry WHERE id = :id") suspend fun getAllergy(id: String): AllergyEntry? + @Query(+ "SELECT * FROM AllergyEntry " ++ "WHERE dataSourceId = :dataSourceId AND fhirResourceId = :fhirResourceId LIMIT 1"+ )+ suspend fun findAllergy(dataSourceId: String, fhirResourceId: String): AllergyEntry?+ // --- Conditions -------------------------------------------------------- @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun upsertCondition(entry: ConditionEntry) - @Insert(onConflict = OnConflictStrategy.REPLACE)- suspend fun upsertConditions(entries: List<ConditionEntry>)- @Delete suspend fun deleteCondition(entry: ConditionEntry) @@ -333,14 +357,17 @@ interface MedicalDao { @Query("SELECT * FROM ConditionEntry WHERE id = :id") suspend fun getCondition(id: String): ConditionEntry? + @Query(+ "SELECT * FROM ConditionEntry " ++ "WHERE dataSourceId = :dataSourceId AND fhirResourceId = :fhirResourceId LIMIT 1"+ )+ suspend fun findCondition(dataSourceId: String, fhirResourceId: String): ConditionEntry?+ // --- Lab results ------------------------------------------------------- @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun upsertLabResult(entry: LabResultEntry) - @Insert(onConflict = OnConflictStrategy.REPLACE)- suspend fun upsertLabResults(entries: List<LabResultEntry>)- @Delete suspend fun deleteLabResult(entry: LabResultEntry) @@ -350,6 +377,12 @@ interface MedicalDao { @Query("SELECT * FROM LabResultEntry WHERE id = :id") suspend fun getLabResult(id: String): LabResultEntry? + @Query(+ "SELECT * FROM LabResultEntry " ++ "WHERE dataSourceId = :dataSourceId AND fhirResourceId = :fhirResourceId LIMIT 1"+ )+ suspend fun findLabResult(dataSourceId: String, fhirResourceId: String): LabResultEntry?+ // --- Profile ----------------------------------------------------------- @Insert(onConflict = OnConflictStrategy.REPLACE)@@ -378,9 +411,6 @@ interface MedicalDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun upsertDoseEvent(event: DoseEvent) - @Insert(onConflict = OnConflictStrategy.REPLACE)- suspend fun upsertDoseEvents(events: List<DoseEvent>)- @Delete suspend fun deleteDoseEvent(event: DoseEvent) @@ -395,4 +425,36 @@ interface MedicalDao { @Query("DELETE FROM DoseEvent WHERE medicationId = :medicationId") suspend fun deleteDosesFor(medicationId: String)++ @Query("SELECT * FROM DoseEvent WHERE medicationId = :medicationId")+ suspend fun getDosesFor(medicationId: String): List<DoseEvent>++ @Query(+ "SELECT * FROM DoseEvent " ++ "WHERE dataSourceId = :dataSourceId AND fhirResourceId = :fhirResourceId LIMIT 1"+ )+ suspend fun findDoseEvent(dataSourceId: String, fhirResourceId: String): DoseEvent?++ // --- Health Connect bookkeeping ---------------------------------------++ @Insert(onConflict = OnConflictStrategy.REPLACE)+ suspend fun upsertTombstone(tombstone: DeletedMedicalResource)++ @Query(+ "SELECT EXISTS(SELECT 1 FROM DeletedMedicalResource WHERE kind = :kind " ++ "AND dataSourceId = :dataSourceId AND fhirResourceId = :fhirResourceId)"+ )+ suspend fun isTombstoned(kind: MedicalKind, dataSourceId: String, fhirResourceId: String): Boolean++ @Query("SELECT * FROM DeletedMedicalResource WHERE retryDelete = 1 AND dataSourceId = :dataSourceId")+ suspend fun getPendingRemoteDeletes(dataSourceId: String): List<DeletedMedicalResource>++ @Insert(onConflict = OnConflictStrategy.IGNORE)+ suspend fun insertPendingMirror(pending: PendingMirror)++ @Query("DELETE FROM PendingMirror WHERE kind = :kind AND rowId = :rowId")+ suspend fun deletePendingMirror(kind: MedicalKind, rowId: String)++ @Query("SELECT * FROM PendingMirror")+ suspend fun getPendingMirrors(): List<PendingMirror> }
health/src/main/java/com/vayunmathur/health/data/Record.kt
diff --git a/health/src/main/java/com/vayunmathur/health/data/Record.kt b/health/src/main/java/com/vayunmathur/health/data/Record.ktindex 60dffec602..591260343b 100644--- a/health/src/main/java/com/vayunmathur/health/data/Record.kt+++ b/health/src/main/java/com/vayunmathur/health/data/Record.kt@@ -369,8 +369,9 @@ interface HealthDao { VaccinationEntry::class, MedicationEntry::class, MedicalAttachment::class, MedicationSchedule::class, AllergyEntry::class, ConditionEntry::class, LabResultEntry::class, HealthProfile::class, ProfileAnswer::class, DoseEvent::class,+ DeletedMedicalResource::class, PendingMirror::class, ],- version = 11,+ version = 12, exportSchema = false ) @ColumnTypeConverters(Converters::class)@@ -571,6 +572,44 @@ abstract class HealthDatabase : RoomDatabase() { "CREATE INDEX IF NOT EXISTS index_DoseEvent_medicationId_takenAt " + "ON DoseEvent (medicationId, takenAt)" )+ },+ Migration(11, 12) {+ it.execSQL(+ """+ CREATE TABLE IF NOT EXISTS DeletedMedicalResource (+ kind TEXT NOT NULL,+ dataSourceId TEXT NOT NULL,+ fhirResourceId TEXT NOT NULL,+ fhirResourceType INTEGER NOT NULL,+ retryDelete INTEGER NOT NULL,+ PRIMARY KEY(kind, dataSourceId, fhirResourceId)+ )+ """.trimIndent()+ )+ it.execSQL(+ """+ CREATE TABLE IF NOT EXISTS PendingMirror (+ kind TEXT NOT NULL,+ rowId TEXT NOT NULL,+ PRIMARY KEY(kind, rowId)+ )+ """.trimIndent()+ )+ // Anything that never reached Health Connect gets queued, so the first sync on the+ // new version pushes it rather than leaving it local forever.+ listOf(+ "Vaccination" to "VaccinationEntry",+ "Medication" to "MedicationEntry",+ "Dose" to "DoseEvent",+ "Allergy" to "AllergyEntry",+ "Condition" to "ConditionEntry",+ "LabResult" to "LabResultEntry",+ ).forEach { (kind, table) ->+ it.execSQL(+ "INSERT OR IGNORE INTO PendingMirror (kind, rowId) " ++ "SELECT '$kind', id FROM $table WHERE fhirResourceId IS NULL"+ )+ } } ) }
health/src/main/java/com/vayunmathur/health/domain/FhirAllergyCondition.kt
diff --git a/health/src/main/java/com/vayunmathur/health/domain/FhirAllergyCondition.kt b/health/src/main/java/com/vayunmathur/health/domain/FhirAllergyCondition.ktindex 649940a192..8c9376f577 100644--- a/health/src/main/java/com/vayunmathur/health/domain/FhirAllergyCondition.kt+++ b/health/src/main/java/com/vayunmathur/health/domain/FhirAllergyCondition.kt@@ -16,7 +16,7 @@ import java.time.Instant internal fun allergyIntoleranceJson(entry: AllergyEntry): String = buildJsonObject { put("resourceType", "AllergyIntolerance")- put("id", entry.id)+ put("id", entry.fhirResourceId ?: entry.id) // An allergy list is only safe to act on if "not currently allergic" is distinguishable // from "never recorded", so clinicalStatus is always written rather than left implicit. putJsonObject("clinicalStatus") {@@ -53,7 +53,7 @@ internal fun allergyIntoleranceJson(entry: AllergyEntry): String = buildJsonObje put("text", entry.displayName) } putJsonObject("patient") { put("reference", "Patient/${FhirRecords.PATIENT_RESOURCE_ID}") }- entry.onsetAt?.let { put("onsetDateTime", formatDateTime(it)) }+ entry.onsetAt?.let { put("onsetDateTime", formatClinicalDate(it)) } put("recordedDate", formatDateTime(entry.recordedAt)) entry.reaction?.takeIf { it.isNotBlank() }?.let { reaction -> putJsonArray("reaction") {@@ -108,7 +108,7 @@ internal fun parseAllergyIntolerance(data: String, dataSourceId: String): Allerg internal fun conditionJson(entry: ConditionEntry): String = buildJsonObject { put("resourceType", "Condition")- put("id", entry.id)+ put("id", entry.fhirResourceId ?: entry.id) putJsonObject("clinicalStatus") { putJsonArray("coding") { add(@@ -153,8 +153,8 @@ internal fun conditionJson(entry: ConditionEntry): String = buildJsonObject { put("text", entry.displayName) } putJsonObject("subject") { put("reference", "Patient/${FhirRecords.PATIENT_RESOURCE_ID}") }- put("onsetDateTime", formatDateTime(entry.onsetAt))- entry.resolvedAt?.let { put("abatementDateTime", formatDateTime(it)) }+ put("onsetDateTime", formatClinicalDate(entry.onsetAt))+ entry.resolvedAt?.let { put("abatementDateTime", formatClinicalDate(it)) } entry.note?.takeIf { it.isNotBlank() }?.let { putJsonArray("note") { add(buildJsonObject { put("text", it) }) } }
health/src/main/java/com/vayunmathur/health/domain/FhirImmunization.kt
diff --git a/health/src/main/java/com/vayunmathur/health/domain/FhirImmunization.kt b/health/src/main/java/com/vayunmathur/health/domain/FhirImmunization.ktindex 52ac72d406..24f90d0810 100644--- a/health/src/main/java/com/vayunmathur/health/domain/FhirImmunization.kt+++ b/health/src/main/java/com/vayunmathur/health/domain/FhirImmunization.kt@@ -11,6 +11,7 @@ import kotlinx.serialization.json.put import kotlinx.serialization.json.putJsonArray import kotlinx.serialization.json.putJsonObject import java.time.Instant+import java.time.ZoneId internal fun patientJson(): String = buildJsonObject { put("resourceType", "Patient")@@ -22,7 +23,7 @@ internal fun immunizationJson( attachments: List<FhirRecords.FhirAttachment> = emptyList(), ): String = buildJsonObject { put("resourceType", "Immunization")- put("id", entry.id)+ put("id", entry.fhirResourceId ?: entry.id) put("status", "completed") putJsonObject("vaccineCode") { if (entry.cvxCode != null) {@@ -39,7 +40,7 @@ internal fun immunizationJson( put("text", entry.displayName) } putJsonObject("patient") { put("reference", "Patient/${FhirRecords.PATIENT_RESOURCE_ID}") }- put("occurrenceDateTime", formatDateTime(entry.occurredAt))+ put("occurrenceDateTime", formatClinicalDate(entry.occurredAt)) entry.lotNumber?.takeIf { it.isNotBlank() }?.let { put("lotNumber", it) } entry.site?.takeIf { it.isNotBlank() }?.let { putJsonObject("site") { put("text", it) } } entry.route?.takeIf { it.isNotBlank() }?.let { putJsonObject("route") { put("text", it) } }@@ -130,24 +131,21 @@ internal fun parseQuantity(text: String): Pair<Double, String>? { return if (unit.isEmpty()) null else value to unit } -/** Known shapes of `occurrenceDateTime`, from most to least precise. */-private val DATE_TIME_PARSERS: List<(String) -> Instant> = listOf(+/**+ * Known shapes of a FHIR `dateTime`, from most to least precise.+ *+ * Partial dates land on local midnight, which is how this app stores a date it picked itself.+ * Anchoring them in UTC would show them a day early anywhere west of Greenwich.+ */+private fun dateTimeParsers(zone: ZoneId): List<(String) -> Instant> = listOf( { text -> Instant.parse(text) }, { text -> java.time.OffsetDateTime.parse(text).toInstant() },- { text ->- java.time.LocalDate.parse(text).atStartOfDay(java.time.ZoneOffset.UTC).toInstant()- },- { text ->- java.time.YearMonth.parse(text).atDay(1)- .atStartOfDay(java.time.ZoneOffset.UTC).toInstant()- },- { text ->- java.time.Year.parse(text).atDay(1)- .atStartOfDay(java.time.ZoneOffset.UTC).toInstant()- },+ { text -> java.time.LocalDate.parse(text).atStartOfDay(zone).toInstant() },+ { text -> java.time.YearMonth.parse(text).atDay(1).atStartOfDay(zone).toInstant() },+ { text -> java.time.Year.parse(text).atDay(1).atStartOfDay(zone).toInstant() }, ) -internal fun parseDateTime(text: String?): Instant? {+internal fun parseDateTime(text: String?, zone: ZoneId = ZoneId.systemDefault()): Instant? { if (text.isNullOrBlank()) return null- return DATE_TIME_PARSERS.firstNotNullOfOrNull { parser -> runCatching { parser(text) }.getOrNull() }+ return dateTimeParsers(zone).firstNotNullOfOrNull { parser -> runCatching { parser(text) }.getOrNull() } }
health/src/main/java/com/vayunmathur/health/domain/FhirJson.kt
diff --git a/health/src/main/java/com/vayunmathur/health/domain/FhirJson.kt b/health/src/main/java/com/vayunmathur/health/domain/FhirJson.ktindex 89d3ddb5a5..24c647cca0 100644--- a/health/src/main/java/com/vayunmathur/health/domain/FhirJson.kt+++ b/health/src/main/java/com/vayunmathur/health/domain/FhirJson.kt@@ -10,6 +10,8 @@ import kotlinx.serialization.json.put import kotlinx.serialization.json.putJsonArray import kotlinx.serialization.json.putJsonObject import java.time.Instant+import java.time.LocalTime+import java.time.ZoneId import java.time.format.DateTimeFormatter internal val fhirJson = Json { ignoreUnknownKeys = true }@@ -93,5 +95,34 @@ internal fun JsonObjectBuilder.putQuantity(value: Double, unit: String?) { internal fun formatDateTime(instant: Instant): String = DateTimeFormatter.ISO_INSTANT.format(instant.truncatedTo(java.time.temporal.ChronoUnit.SECONDS)) +/**+ * A date picked from a calendar as a FHIR `date`, anything else as a full `dateTime`.+ *+ * Date-precision fields are stored as local midnight. Writing that as a UTC instant puts it on the+ * previous day for any reader east of UTC, so a value sitting exactly on local midnight is written+ * as the bare date it stands for.+ */+internal fun formatClinicalDate(instant: Instant, zone: ZoneId = ZoneId.systemDefault()): String {+ val local = instant.atZone(zone)+ return if (local.toLocalTime() == LocalTime.MIDNIGHT) {+ local.toLocalDate().toString()+ } else {+ formatDateTime(instant)+ }+}++private const val ENTERED_IN_ERROR = "entered-in-error"++/**+ * Whether the author has retracted this resource.+ *+ * Most types say so in `status`; AllergyIntolerance and Condition say it in `verificationStatus`.+ */+internal fun isEnteredInError(data: String): Boolean {+ val root = parseObject(data) ?: return false+ return root.string("status") == ENTERED_IN_ERROR ||+ (root["verificationStatus"] as? JsonObject).clinicalStatusCode() == ENTERED_IN_ERROR+}+ internal fun formatQuantity(value: Double): String = if (value == value.toLong().toDouble()) value.toLong().toString() else value.toString()
health/src/main/java/com/vayunmathur/health/domain/FhirMedication.kt
diff --git a/health/src/main/java/com/vayunmathur/health/domain/FhirMedication.kt b/health/src/main/java/com/vayunmathur/health/domain/FhirMedication.ktindex dae03edede..2069e24eb1 100644--- a/health/src/main/java/com/vayunmathur/health/domain/FhirMedication.kt+++ b/health/src/main/java/com/vayunmathur/health/domain/FhirMedication.kt@@ -10,7 +10,7 @@ import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonObjectBuilder import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.buildJsonObject-import kotlinx.serialization.json.intOrNull+import kotlinx.serialization.json.doubleOrNull import kotlinx.serialization.json.jsonPrimitive import kotlinx.serialization.json.put import kotlinx.serialization.json.putJsonArray@@ -28,20 +28,40 @@ import kotlinx.datetime.LocalDate as KotlinLocalDate * assert that the whole course had been consumed. * * `intent` is `plan` rather than `order` because nobody prescribed this — it is the user's own- * account of what they intend to take. When a [schedule] is given it becomes- * `dosageInstruction.timing.repeat`, which is what makes the reminder times part of the record- * rather than a detail this app keeps to itself.+ * account of what they intend to take. The course dates always travel as+ * `dosageInstruction.timing.repeat.boundsPeriod`, since MedicationRequest has no other field for+ * them; a [schedule] adds the reminder times to the same `repeat`. */ internal fun medicationRequestJson( entry: MedicationEntry, schedule: MedicationSchedule? = null, ): String = buildJsonObject { put("resourceType", "MedicationRequest")- put("id", entry.id)+ put("id", entry.fhirId()) put("status", requestStatusToFhir(entry.status)) put("intent", "plan") // The user is the source. Without this a reader would assume a clinician entered it. put("reportedBoolean", true)+ putMedicationConcept(entry)+ putJsonObject("subject") { put("reference", "Patient/${FhirRecords.PATIENT_RESOURCE_ID}") }+ put("authoredOn", formatClinicalDate(entry.startedAt))++ putJsonArray("dosageInstruction") {+ add(+ buildJsonObject {+ entry.dosageText?.takeIf { it.isNotBlank() }?.let { put("text", it) }+ putJsonObject("timing") { putRepeat(entry, schedule) }+ }+ )+ }+ entry.note?.takeIf { it.isNotBlank() }?.let {+ putJsonArray("note") { add(buildJsonObject { put("text", it) }) }+ }+}.toString()++private fun MedicationEntry.fhirId(): String = fhirResourceId ?: id++private fun JsonObjectBuilder.putMedicationConcept(entry: MedicationEntry) { putJsonObject("medicationCodeableConcept") { if (entry.rxcui != null) { putJsonArray("coding") {@@ -56,54 +76,42 @@ internal fun medicationRequestJson( } put("text", fullMedicationName(entry)) }- putJsonObject("subject") { put("reference", "Patient/${FhirRecords.PATIENT_RESOURCE_ID}") }- put("authoredOn", formatDateTime(entry.startedAt))-- val dosageText = entry.dosageText?.takeIf { it.isNotBlank() }- if (dosageText != null || schedule != null) {- putJsonArray("dosageInstruction") {- add(- buildJsonObject {- dosageText?.let { put("text", it) }- schedule?.let { putJsonObject("timing") { putRepeat(it, entry) } }- }- )- }- }- entry.note?.takeIf { it.isNotBlank() }?.let {- putJsonArray("note") { add(buildJsonObject { put("text", it) }) }- }-}.toString()+} /**- * The dose schedule as a FHIR `Timing.repeat`.+ * The course dates and, when there is one, the dose schedule as a FHIR `Timing.repeat`. *- * The app's own model maps onto this almost exactly: times of day become `timeOfDay`, the- * interval and its unit become `period` and `periodUnit`, chosen weekdays become `dayOfWeek`,- * and the start and end dates become `boundsPeriod`.+ * Times of day become `timeOfDay`, the interval and its unit become `period` and `periodUnit`,+ * and chosen weekdays become `dayOfWeek`. */-private fun JsonObjectBuilder.putRepeat(- schedule: MedicationSchedule,- entry: MedicationEntry,-) {+private fun JsonObjectBuilder.putRepeat(entry: MedicationEntry, schedule: MedicationSchedule?) { putJsonObject("repeat") { putJsonObject("boundsPeriod") {- put("start", formatDateTime(entry.startedAt))- val end = schedule.endDate?.let { formatScheduleDate(it) }- ?: entry.endedAt?.let { formatDateTime(it) }+ put("start", formatClinicalDate(entry.startedAt))+ // A finished course ends when it ended. An ongoing one ends when its reminders do,+ // if they are set to.+ val end = entry.endedAt?.takeIf { entry.status != MedicationStatus.Active }+ ?.let { formatClinicalDate(it) }+ ?: schedule?.endDate?.let { formatScheduleDate(it) } end?.let { put("end", it) } }+ if (schedule == null) return@putJsonObject++ val weekly = schedule.repeatUnit == RepeatUnit.Weekly+ val doseDays = Integer.bitCount(schedule.daysOfWeek and ALL_DAYS_MASK) if (schedule.times.isNotEmpty()) { putJsonArray("timeOfDay") { schedule.times.sorted().forEach { add(JsonPrimitive(formatTimeOfDay(it))) } }- // frequency is the number of times per period, which for a list of clock times is- // simply how many there are.- put("frequency", schedule.times.size)+ // frequency counts doses per period, so a weekly schedule multiplies its times of+ // day by the number of days it falls on.+ if (!weekly || doseDays > 0) {+ put("frequency", schedule.times.size * (if (weekly) doseDays else 1))+ } } put("period", schedule.interval)- put("periodUnit", if (schedule.repeatUnit == RepeatUnit.Weekly) "wk" else "d")- if (schedule.repeatUnit == RepeatUnit.Weekly && schedule.daysOfWeek != 0) {+ put("periodUnit", if (weekly) "wk" else "d")+ if (weekly && doseDays > 0) { putJsonArray("dayOfWeek") { FHIR_DAYS.forEachIndexed { index, day -> if (schedule.daysOfWeek and (1 shl index) != 0) add(JsonPrimitive(day))@@ -115,6 +123,7 @@ private fun JsonObjectBuilder.putRepeat( /** Bit 0 is Sunday, matching `MedicationSchedule.daysOfWeek`. */ private val FHIR_DAYS = listOf("sun", "mon", "tue", "wed", "thu", "fri", "sat")+private const val ALL_DAYS_MASK = 0x7F /** A schedule date as a FHIR `date`. */ private fun formatScheduleDate(date: KotlinLocalDate): String =@@ -125,8 +134,8 @@ private fun formatScheduleDate(date: KotlinLocalDate): String = * * Local rather than UTC because a schedule anchored "today" means the user's today. */-internal fun Instant.toScheduleDate(): KotlinLocalDate {- val local = atZone(ZoneId.systemDefault()).toLocalDate()+internal fun Instant.toScheduleDate(zone: ZoneId = ZoneId.systemDefault()): KotlinLocalDate {+ val local = atZone(zone).toLocalDate() return KotlinLocalDate(local.year, local.monthValue, local.dayOfMonth) } @@ -142,11 +151,23 @@ internal fun fullMedicationName(entry: MedicationEntry): String = entry.doseForm?.takeIf { it.isNotBlank() }, ).joinToString(" ") +/** The display name and RxNorm code of a `medicationCodeableConcept`, or null with no name. */+private fun JsonObject.medicationName(): Pair<String, String?>? {+ val concept = this["medicationCodeableConcept"] as? JsonObject+ val coding = concept.codingWithSystem(FhirRecords.RXNORM_SYSTEM)+ val displayName = coding?.string("display")+ ?: concept?.string("text")+ ?: concept.anyCoding()?.string("display")+ ?: return null+ return displayName to coding?.string("code")+}+ /** * A medication regimen read back from a `MedicationRequest`. *- * Returns the entry and, when the request carries a `timing.repeat`, the schedule behind it —- * a provider's instructions are worth keeping rather than flattening to a date range.+ * Returns the entry and, when the request carries a `timing.repeat` this app can represent, the+ * schedule behind it — a provider's instructions are worth keeping rather than flattening to a+ * date range. The entry's `id` is the FHIR id; the importer assigns the local row id. */ internal fun parseMedicationRequest( data: String,@@ -155,42 +176,85 @@ internal fun parseMedicationRequest( val root = parseObject(data) ?: return null if (root.string("resourceType") != "MedicationRequest") return null val id = root.string("id") ?: return null- val concept = root["medicationCodeableConcept"] as? JsonObject- val coding = concept.codingWithSystem(FhirRecords.RXNORM_SYSTEM)- val displayName = coding?.string("display")- ?: concept?.string("text")- ?: concept.anyCoding()?.string("display")- ?: return null+ val status = requestStatusFromFhir(root.string("status")) ?: return null+ val (displayName, rxcui) = root.medicationName() ?: return null val dosage = (root["dosageInstruction"] as? JsonArray)?.firstOrNull() as? JsonObject val repeat = ((dosage?.get("timing") as? JsonObject)?.get("repeat")) as? JsonObject val bounds = repeat?.get("boundsPeriod") as? JsonObject - val startedAt = parseDateTime(root.string("authoredOn"))- ?: parseDateTime(bounds.string("start"))+ // boundsPeriod is when dosing runs; authoredOn is when the request was written, which for a+ // prescription can be well before the first dose.+ val startedAt = parseDateTime(bounds.string("start"))+ ?: parseDateTime(root.string("authoredOn")) ?: return null- val endedAt = parseDateTime(bounds.string("end"))+ val boundsEnd = parseDateTime(bounds.string("end")) val entry = MedicationEntry( id = id,- rxcui = coding?.string("code"),+ rxcui = rxcui,+ displayName = displayName,+ status = status,+ startedAt = startedAt,+ // An ongoing course's end is only planned, and belongs to the reminders.+ endedAt = boundsEnd?.takeIf { status != MedicationStatus.Active },+ dosageText = dosage?.string("text"),+ note = root.firstNoteText(),+ fhirResourceId = id,+ dataSourceId = dataSourceId,+ )+ return entry to repeat?.let { parseRepeat(it, id, startedAt, boundsEnd) }+}++/**+ * A medication a provider reports the patient as taking, from a `MedicationStatement` that is not+ * a dose against one of this app's plans.+ */+internal fun parseMedicationStatement(data: String, dataSourceId: String): MedicationEntry? {+ val root = parseObject(data) ?: return null+ if (root.string("resourceType") != "MedicationStatement") return null+ if (root.basedOnRequestId() != null) return null+ val id = root.string("id") ?: return null+ val status = statementStatusFromFhir(root.string("status")) ?: return null+ val (displayName, rxcui) = root.medicationName() ?: return null++ val period = root["effectivePeriod"] as? JsonObject+ val startedAt = parseDateTime(root.string("effectiveDateTime"))+ ?: parseDateTime(period.string("start"))+ ?: parseDateTime(root.string("dateAsserted"))+ ?: return null+ val dosage = (root["dosage"] as? JsonArray)?.firstOrNull() as? JsonObject++ return MedicationEntry(+ id = id,+ rxcui = rxcui, displayName = displayName,- status = requestStatusFromFhir(root.string("status")),+ status = status, startedAt = startedAt,- endedAt = endedAt,+ endedAt = parseDateTime(period.string("end"))?.takeIf { status != MedicationStatus.Active }, dosageText = dosage?.string("text"), note = root.firstNoteText(), fhirResourceId = id, dataSourceId = dataSourceId, )- return entry to repeat?.let { parseRepeat(it, id, startedAt, endedAt) }+}++/**+ * Whether this is a `MedicationStatement` with no plan behind it.+ *+ * From this app's own data source that can only be a regimen an earlier build wrote as a+ * statement, before medications moved to `MedicationRequest`.+ */+internal fun isUnplannedMedicationStatement(data: String): Boolean {+ val root = parseObject(data) ?: return false+ return root.string("resourceType") == "MedicationStatement" && root.basedOnRequestId() == null } private fun parseRepeat( repeat: JsonObject, medicationId: String, startedAt: Instant,- endedAt: Instant?,+ endsAt: Instant?, ): MedicationSchedule? { val times = (repeat["timeOfDay"] as? JsonArray) ?.mapNotNull { (it as? JsonPrimitive)?.content?.let(::parseTimeOfDay) }@@ -198,13 +262,33 @@ private fun parseRepeat( // Without clock times there is nothing to remind at, whatever else the timing says. if (times.isEmpty()) return null - val unit = if (repeat.string("periodUnit") == "wk") RepeatUnit.Weekly else RepeatUnit.Daily+ // period is a decimal in FHIR. Only whole days or weeks fit this app's model; anything else+ // is refused rather than rounded into a different regimen.+ val period = repeat["period"]?.jsonPrimitive?.doubleOrNull ?: 1.0+ if (period < 1 || period % 1.0 != 0.0) return null+ var interval = period.toInt()++ var unit = when (repeat.string("periodUnit")) {+ null, "d" -> RepeatUnit.Daily+ "wk" -> RepeatUnit.Weekly+ // Hours, minutes, months and years cannot be expressed as days or weeks. Reading "every 8+ // hours" as "every 8 days" would be a wrong regimen, so no schedule is better.+ else -> return null+ } val days = (repeat["dayOfWeek"] as? JsonArray) ?.mapNotNull { (it as? JsonPrimitive)?.content } ?.fold(0) { acc, day -> val index = FHIR_DAYS.indexOf(day) if (index < 0) acc else acc or (1 shl index) } ?: 0+ if (unit == RepeatUnit.Daily && days != 0) {+ // Daily on chosen weekdays is weekly on those days. With a multi-day period as well the+ // two constraints do not combine into anything this model can say.+ if (interval != 1) return null+ unit = RepeatUnit.Weekly+ interval = 1+ }+ if (unit == RepeatUnit.Weekly && days == 0) return null return MedicationSchedule( id = medicationId,@@ -214,10 +298,10 @@ private fun parseRepeat( enabled = false, times = times.distinct().sorted(), repeatUnit = unit,- interval = repeat["period"]?.jsonPrimitive?.intOrNull?.coerceAtLeast(1) ?: 1,+ interval = interval, daysOfWeek = days, anchorDate = startedAt.toScheduleDate(),- endDate = endedAt?.toScheduleDate(),+ endDate = endsAt?.toScheduleDate(), ) } @@ -244,25 +328,12 @@ private fun parseTimeOfDay(value: String): Int? { */ internal fun doseEventJson(event: DoseEvent, medication: MedicationEntry): String = buildJsonObject { put("resourceType", "MedicationStatement")- put("id", event.id)+ put("id", event.fhirResourceId ?: event.id) put("status", "completed") putJsonArray("basedOn") {- add(buildJsonObject { put("reference", "MedicationRequest/${event.medicationId}") })- }- putJsonObject("medicationCodeableConcept") {- if (medication.rxcui != null) {- putJsonArray("coding") {- add(- buildJsonObject {- put("system", FhirRecords.RXNORM_SYSTEM)- put("code", medication.rxcui)- put("display", fullMedicationName(medication))- }- )- }- }- put("text", fullMedicationName(medication))+ add(buildJsonObject { put("reference", "MedicationRequest/${medication.fhirId()}") }) }+ putMedicationConcept(medication) putJsonObject("subject") { put("reference", "Patient/${FhirRecords.PATIENT_RESOURCE_ID}") } // A moment, not a period: this is one dose, not a course of them. put("effectiveDateTime", formatDateTime(event.takenAt))@@ -272,26 +343,39 @@ internal fun doseEventJson(event: DoseEvent, medication: MedicationEntry): Strin } }.toString() +/**+ * A dose read back from a `MedicationStatement`.+ *+ * [DoseEvent.medicationId] holds the FHIR id of the MedicationRequest it is based on; the importer+ * resolves that to a local row. Only `completed` statements are doses — `not-taken`, `intended`+ * and the rest say something else, and recording them as taken would invent history.+ */ internal fun parseDoseEvent(data: String, dataSourceId: String): DoseEvent? { val root = parseObject(data) ?: return null if (root.string("resourceType") != "MedicationStatement") return null+ if (root.string("status") != "completed") return null val id = root.string("id") ?: return null val takenAt = parseDateTime(root.string("effectiveDateTime")) ?: return null- val medicationId = (root["basedOn"] as? JsonArray)- ?.firstNotNullOfOrNull { (it as? JsonObject).string("reference") }- ?.substringAfter("MedicationRequest/", "")- ?.takeIf { it.isNotEmpty() }- ?: return null+ val requestId = root.basedOnRequestId() ?: return null return DoseEvent( id = id,- medicationId = medicationId,+ medicationId = requestId, takenAt = takenAt, fhirResourceId = id, dataSourceId = dataSourceId, ) } +/** The id of the MedicationRequest in `basedOn`, from a relative or absolute reference. */+private fun JsonObject.basedOnRequestId(): String? =+ (this["basedOn"] as? JsonArray)+ ?.firstNotNullOfOrNull { (it as? JsonObject).string("reference") }+ ?.takeIf { "MedicationRequest/" in it }+ ?.substringAfterLast("MedicationRequest/")+ ?.substringBefore("/_history")+ ?.takeIf { it.isNotEmpty() }+ /** * [MedicationStatus] as a `MedicationRequest.status`. *@@ -304,8 +388,17 @@ private fun requestStatusToFhir(status: MedicationStatus): String = when (status MedicationStatus.Stopped -> "stopped" } -private fun requestStatusFromFhir(status: String?): MedicationStatus = when (status) {+/** Null for `entered-in-error`: a retracted record is not a medication at all. */+private fun requestStatusFromFhir(status: String?): MedicationStatus? = when (status) {+ "entered-in-error" -> null+ "completed" -> MedicationStatus.Completed+ "stopped", "cancelled" -> MedicationStatus.Stopped+ else -> MedicationStatus.Active+}++private fun statementStatusFromFhir(status: String?): MedicationStatus? = when (status) {+ "entered-in-error" -> null "completed" -> MedicationStatus.Completed- "stopped", "cancelled", "entered-in-error" -> MedicationStatus.Stopped+ "stopped", "not-taken" -> MedicationStatus.Stopped else -> MedicationStatus.Active }
health/src/main/java/com/vayunmathur/health/domain/FhirObservations.kt
diff --git a/health/src/main/java/com/vayunmathur/health/domain/FhirObservations.kt b/health/src/main/java/com/vayunmathur/health/domain/FhirObservations.ktindex f18468bed6..c9ef50a084 100644--- a/health/src/main/java/com/vayunmathur/health/domain/FhirObservations.kt+++ b/health/src/main/java/com/vayunmathur/health/domain/FhirObservations.kt@@ -22,7 +22,7 @@ import java.time.Instant */ internal fun labResultJson(entry: LabResultEntry): String = buildJsonObject { put("resourceType", "Observation")- put("id", entry.id)+ put("id", entry.fhirResourceId ?: entry.id) put("status", "final") putObservationCategory("laboratory") putJsonObject("code") {@@ -40,7 +40,7 @@ internal fun labResultJson(entry: LabResultEntry): String = buildJsonObject { put("text", entry.displayName) } putJsonObject("subject") { put("reference", "Patient/${FhirRecords.PATIENT_RESOURCE_ID}") }- put("effectiveDateTime", formatDateTime(entry.takenAt))+ put("effectiveDateTime", formatClinicalDate(entry.takenAt)) val numeric = entry.value if (numeric != null) {@@ -104,7 +104,7 @@ internal fun pregnancyStatusJson( add( buildJsonObject { putCoded("code", FhirRecords.LOINC_SYSTEM, "11778-8", "Estimated date of delivery")- put("valueDateTime", formatDateTime(it))+ put("valueDateTime", formatClinicalDate(it)) } ) }
health/src/main/java/com/vayunmathur/health/domain/FhirRecords.kt
diff --git a/health/src/main/java/com/vayunmathur/health/domain/FhirRecords.kt b/health/src/main/java/com/vayunmathur/health/domain/FhirRecords.ktindex 7d5e16c7ef..0dc0efa2ea 100644--- a/health/src/main/java/com/vayunmathur/health/domain/FhirRecords.kt+++ b/health/src/main/java/com/vayunmathur/health/domain/FhirRecords.kt@@ -10,15 +10,16 @@ import com.vayunmathur.health.data.PregnancyStatus import com.vayunmathur.health.data.SmokingStatus import com.vayunmathur.health.data.VaccinationEntry import java.time.Instant+import java.time.ZoneId /** * Builds and reads the FHIR R4 JSON that Health Connect's Personal Health Record store accepts. * * Health Connect takes the resource as an opaque JSON string and validates it against the spec, so * the required fields below are not optional decoration: `Immunization` must carry `status`,- * `vaccineCode`, `patient` and an `occurrence[x]`, and `MedicationStatement` must carry `status`,- * `subject` and a `medication[x]`. Both reference a `Patient`, which is why [patientJson] exists and- * is written to the same data source before anything else.+ * `vaccineCode`, `patient` and an `occurrence[x]`, and `MedicationRequest` and `MedicationStatement`+ * must carry `status`, `subject` and a `medication[x]`. All of them reference a `Patient`, which is+ * why [patientJson] exists and is written to the same data source before anything else. * * Reading is deliberately far more forgiving than writing. Resources synced from a real health system * are shown alongside the user's own, and those carry codings, extensions and date precisions this@@ -107,6 +108,15 @@ object FhirRecords { fun parseDoseEvent(data: String, dataSourceId: String): DoseEvent? = com.vayunmathur.health.domain.parseDoseEvent(data, dataSourceId) + fun parseMedicationStatement(data: String, dataSourceId: String): MedicationEntry? =+ com.vayunmathur.health.domain.parseMedicationStatement(data, dataSourceId)++ fun isUnplannedMedicationStatement(data: String): Boolean =+ com.vayunmathur.health.domain.isUnplannedMedicationStatement(data)++ fun isEnteredInError(data: String): Boolean =+ com.vayunmathur.health.domain.isEnteredInError(data)+ fun parseAllergyIntolerance(data: String, dataSourceId: String): AllergyEntry? = com.vayunmathur.health.domain.parseAllergyIntolerance(data, dataSourceId) @@ -161,11 +171,11 @@ object FhirRecords { /** * FHIR `dateTime` allows YYYY, YYYY-MM and YYYY-MM-DD as well as a full timestamp, and a provider- * feed uses all of them. Partial dates are anchored to the start of their first day in UTC, which- * is the wrong hour but the right day, and the log only ever shows the day.+ * feed uses all of them. Partial dates are anchored to local midnight in [zone], the same way+ * this app stores a date it picked itself, so they show on the day they name. */- internal fun parseDateTime(text: String?): Instant? =- com.vayunmathur.health.domain.parseDateTime(text)+ internal fun parseDateTime(text: String?, zone: ZoneId = ZoneId.systemDefault()): Instant? =+ com.vayunmathur.health.domain.parseDateTime(text, zone) /** Splits "0.5 mL" into 0.5 and "mL". Null when the text does not start with a number. */ internal fun parseQuantity(text: String): Pair<Double, String>? =
health/src/main/java/com/vayunmathur/health/platform/DoseActionReceiver.kt
diff --git a/health/src/main/java/com/vayunmathur/health/platform/DoseActionReceiver.kt b/health/src/main/java/com/vayunmathur/health/platform/DoseActionReceiver.ktindex c6c851f460..6d41f18f0e 100644--- a/health/src/main/java/com/vayunmathur/health/platform/DoseActionReceiver.kt+++ b/health/src/main/java/com/vayunmathur/health/platform/DoseActionReceiver.kt@@ -1,22 +1,16 @@-@file:OptIn(kotlin.uuid.ExperimentalUuidApi::class)- package com.vayunmathur.health.platform import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import com.vayunmathur.library.log.Log-import com.vayunmathur.health.data.DoseEvent import com.vayunmathur.health.data.HealthRepository-import com.vayunmathur.health.domain.FhirRecords import com.vayunmathur.health.notifications.DoseNotification import com.vayunmathur.health.service.DoseSoundService import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.launch-import java.time.Instant-import kotlin.uuid.Uuid /** * Handles Taken and Snooze, from either the notification actions or the full-screen reminder.@@ -47,36 +41,21 @@ class DoseActionReceiver : BroadcastReceiver() { /** * Writes the dose locally, then mirrors it to Health Connect. *- * Local first, and the mirror is allowed to fail: the alarm may have woken a process where- * nothing has set up the Health Connect client, and losing the record of a dose the user- * explicitly acknowledged would be much worse than an un-mirrored row. A later import reconciles.+ * The alarm may have started a process where `MainActivity` never ran, so the Health Connect+ * client is set up here. If the mirror still fails the dose stays queued for the next sync;+ * losing a dose the user explicitly acknowledged would be much worse than a late mirror. */- // Broad catch below is deliberate: the alarm may have woken a process where nothing- // has set up the Health Connect client, and losing the record of an acknowledged dose- // would be much worse than an un-mirrored row. A later import reconciles.+ // Broad catch below is deliberate: onReceive must not throw, and Room plus the Health+ // Connect client throw undocumented RuntimeExceptions. @Suppress("TooGenericExceptionCaught") private fun recordTaken(context: Context, medicationId: String) { val repository = HealthRepository.get(context) val pendingResult = goAsync() CoroutineScope(SupervisorJob() + Dispatchers.IO).launch { try {- val event = DoseEvent(- id = Uuid.random().toString(),- medicationId = medicationId,- takenAt = Instant.now(),- )- repository.upsertDoseEvent(event)+ PersonalHealthRecords.ensureInitialized(context)+ repository.recordDose(medicationId) Log.status(TAG, "Dose taken for $medicationId")-- val medication = repository.getMedication(medicationId) ?: return@launch- val dataSourceId = PersonalHealthRecords.dataSourceId() ?: return@launch- val written = PersonalHealthRecords.upsert(- dataSourceId,- FhirRecords.doseEventJson(event, medication),- ) ?: return@launch- repository.upsertDoseEvent(- event.copy(fhirResourceId = written, dataSourceId = dataSourceId)- ) } catch (e: Exception) { Log.error(TAG, "Could not record the dose for $medicationId", e) } finally {
health/src/main/java/com/vayunmathur/health/platform/DoseReceiver.kt
diff --git a/health/src/main/java/com/vayunmathur/health/platform/DoseReceiver.kt b/health/src/main/java/com/vayunmathur/health/platform/DoseReceiver.ktindex a1eafb6c3a..9bdff1e13b 100644--- a/health/src/main/java/com/vayunmathur/health/platform/DoseReceiver.kt+++ b/health/src/main/java/com/vayunmathur/health/platform/DoseReceiver.kt@@ -5,6 +5,7 @@ import android.content.Context import android.content.Intent import com.vayunmathur.library.log.Log import com.vayunmathur.health.data.HealthRepository+import com.vayunmathur.health.data.MedicationStatus import com.vayunmathur.health.notifications.DoseNotification import com.vayunmathur.health.service.DoseSoundService import kotlinx.coroutines.CoroutineScope@@ -33,10 +34,14 @@ class DoseReceiver : BroadcastReceiver() { val pendingResult = goAsync() CoroutineScope(SupervisorJob() + Dispatchers.IO).launch { try {- val medication = repository.getMedication(medicationId)- val name = medication?.let {- listOfNotNull(it.displayName, it.strength).joinToString(" ")- } ?: return@launch+ val medication = repository.getMedication(medicationId) ?: return@launch+ // A medication that has since been stopped should not ring, whatever alarm was+ // already armed for it.+ if (medication.status != MedicationStatus.Active) {+ repository.disableReminders(context, medicationId)+ return@launch+ }+ val name = listOfNotNull(medication.displayName, medication.strength).joinToString(" ") DoseNotification.post(context, scheduleId, medicationId, name)
health/src/main/java/com/vayunmathur/health/platform/MedicalClinicalOps.kt
diff --git a/health/src/main/java/com/vayunmathur/health/platform/MedicalClinicalOps.kt b/health/src/main/java/com/vayunmathur/health/platform/MedicalClinicalOps.ktindex 6545134f74..c3dde6a9f2 100644--- a/health/src/main/java/com/vayunmathur/health/platform/MedicalClinicalOps.kt+++ b/health/src/main/java/com/vayunmathur/health/platform/MedicalClinicalOps.kt@@ -4,6 +4,7 @@ import androidx.lifecycle.viewModelScope import com.vayunmathur.health.data.AllergyEntry import com.vayunmathur.health.data.ConditionEntry import com.vayunmathur.health.data.LabResultEntry+import com.vayunmathur.health.data.MedicalKind import com.vayunmathur.health.domain.FhirRecords import kotlinx.coroutines.launch import java.time.Instant@@ -14,7 +15,13 @@ fun MedicalViewModel.saveAllergyDraft() { if (draft.displayName.isBlank()) return viewModelScope.launch { val existing = draft.editingId?.let { repository.getAllergy(it) }- val entry = (existing ?: AllergyEntry(+ val detached = repository.detachIfForeign(+ MedicalKind.Allergy,+ PersonalHealthRecords.allergyResourceType,+ existing?.dataSourceId,+ existing?.fhirResourceId,+ )+ val edited = (existing ?: AllergyEntry( id = Uuid.random().toString(), displayName = "", recordedAt = Instant.now(),@@ -27,7 +34,9 @@ fun MedicalViewModel.saveAllergyDraft() { onsetAt = draft.onsetOn?.toInstant(), note = draft.note.blankToNull(), )+ val entry = if (detached) edited.copy(fhirResourceId = null, dataSourceId = null) else edited repository.upsertAllergy(entry)+ repository.markPending(MedicalKind.Allergy, entry.id) mirrorAllergy(entry.id) } }@@ -35,26 +44,25 @@ fun MedicalViewModel.saveAllergyDraft() { fun MedicalViewModel.deleteAllergy(entry: AllergyEntry) { viewModelScope.launch { repository.deleteAllergy(entry)- val dataSourceId = entry.dataSourceId- val fhirId = entry.fhirResourceId- if (dataSourceId != null && fhirId != null) {- PersonalHealthRecords.delete(- dataSourceId,- PersonalHealthRecords.allergyResourceType,- fhirId,- )- }+ repository.forgetRow(+ MedicalKind.Allergy,+ entry.id,+ PersonalHealthRecords.allergyResourceType,+ entry.dataSourceId,+ entry.fhirResourceId,+ ) } } -private suspend fun MedicalViewModel.mirrorAllergy(id: String) {- val dataSourceId = PersonalHealthRecords.dataSourceId() ?: return- val entry = repository.getAllergy(id) ?: return+internal suspend fun MedicalViewModel.mirrorAllergy(id: String) {+ val entry = repository.getAllergy(id) ?: return repository.clearPending(MedicalKind.Allergy, id)+ val dataSourceId = repository.mirrorTarget(MedicalKind.Allergy, id, entry.dataSourceId) ?: return val written = PersonalHealthRecords.upsert( dataSourceId, FhirRecords.allergyIntoleranceJson(entry), ) ?: return repository.upsertAllergy(entry.copy(fhirResourceId = written, dataSourceId = dataSourceId))+ repository.clearPending(MedicalKind.Allergy, id) } fun MedicalViewModel.saveConditionDraft() {@@ -62,7 +70,13 @@ fun MedicalViewModel.saveConditionDraft() { if (draft.displayName.isBlank()) return viewModelScope.launch { val existing = draft.editingId?.let { repository.getCondition(it) }- val entry = (existing ?: ConditionEntry(+ val detached = repository.detachIfForeign(+ MedicalKind.Condition,+ PersonalHealthRecords.conditionResourceType,+ existing?.dataSourceId,+ existing?.fhirResourceId,+ )+ val edited = (existing ?: ConditionEntry( id = Uuid.random().toString(), displayName = "", onsetAt = Instant.now(),@@ -74,7 +88,9 @@ fun MedicalViewModel.saveConditionDraft() { resolvedAt = draft.resolvedOn?.toInstant(), note = draft.note.blankToNull(), )+ val entry = if (detached) edited.copy(fhirResourceId = null, dataSourceId = null) else edited repository.upsertCondition(entry)+ repository.markPending(MedicalKind.Condition, entry.id) mirrorCondition(entry.id) } }@@ -82,26 +98,25 @@ fun MedicalViewModel.saveConditionDraft() { fun MedicalViewModel.deleteCondition(entry: ConditionEntry) { viewModelScope.launch { repository.deleteCondition(entry)- val dataSourceId = entry.dataSourceId- val fhirId = entry.fhirResourceId- if (dataSourceId != null && fhirId != null) {- PersonalHealthRecords.delete(- dataSourceId,- PersonalHealthRecords.conditionResourceType,- fhirId,- )- }+ repository.forgetRow(+ MedicalKind.Condition,+ entry.id,+ PersonalHealthRecords.conditionResourceType,+ entry.dataSourceId,+ entry.fhirResourceId,+ ) } } -private suspend fun MedicalViewModel.mirrorCondition(id: String) {- val dataSourceId = PersonalHealthRecords.dataSourceId() ?: return- val entry = repository.getCondition(id) ?: return+internal suspend fun MedicalViewModel.mirrorCondition(id: String) {+ val entry = repository.getCondition(id) ?: return repository.clearPending(MedicalKind.Condition, id)+ val dataSourceId = repository.mirrorTarget(MedicalKind.Condition, id, entry.dataSourceId) ?: return val written = PersonalHealthRecords.upsert( dataSourceId, FhirRecords.conditionJson(entry), ) ?: return repository.upsertCondition(entry.copy(fhirResourceId = written, dataSourceId = dataSourceId))+ repository.clearPending(MedicalKind.Condition, id) } fun MedicalViewModel.saveLabDraft() {@@ -109,11 +124,17 @@ fun MedicalViewModel.saveLabDraft() { if (draft.displayName.isBlank()) return viewModelScope.launch { val existing = draft.editingId?.let { repository.getLabResult(it) }+ val detached = repository.detachIfForeign(+ MedicalKind.LabResult,+ PersonalHealthRecords.observationResourceType,+ existing?.dataSourceId,+ existing?.fhirResourceId,+ ) // A result is either a number or a word. Anything that does not parse is kept verbatim // as text rather than being coerced to zero, because "positive" and "trace" are real // results and silently turning one into 0.0 would be a clinically wrong record. val numeric = draft.value.trim().replace(',', '.').toDoubleOrNull()- val entry = (existing ?: LabResultEntry(+ val edited = (existing ?: LabResultEntry( id = Uuid.random().toString(), displayName = "", takenAt = Instant.now(),@@ -128,7 +149,9 @@ fun MedicalViewModel.saveLabDraft() { takenAt = draft.takenOn.toInstant(), note = draft.note.blankToNull(), )+ val entry = if (detached) edited.copy(fhirResourceId = null, dataSourceId = null) else edited repository.upsertLabResult(entry)+ repository.markPending(MedicalKind.LabResult, entry.id) mirrorLabResult(entry.id) } }@@ -136,24 +159,23 @@ fun MedicalViewModel.saveLabDraft() { fun MedicalViewModel.deleteLabResult(entry: LabResultEntry) { viewModelScope.launch { repository.deleteLabResult(entry)- val dataSourceId = entry.dataSourceId- val fhirId = entry.fhirResourceId- if (dataSourceId != null && fhirId != null) {- PersonalHealthRecords.delete(- dataSourceId,- PersonalHealthRecords.observationResourceType,- fhirId,- )- }+ repository.forgetRow(+ MedicalKind.LabResult,+ entry.id,+ PersonalHealthRecords.observationResourceType,+ entry.dataSourceId,+ entry.fhirResourceId,+ ) } } -private suspend fun MedicalViewModel.mirrorLabResult(id: String) {- val dataSourceId = PersonalHealthRecords.dataSourceId() ?: return- val entry = repository.getLabResult(id) ?: return+internal suspend fun MedicalViewModel.mirrorLabResult(id: String) {+ val entry = repository.getLabResult(id) ?: return repository.clearPending(MedicalKind.LabResult, id)+ val dataSourceId = repository.mirrorTarget(MedicalKind.LabResult, id, entry.dataSourceId) ?: return val written = PersonalHealthRecords.upsert( dataSourceId, FhirRecords.labResultJson(entry), ) ?: return repository.upsertLabResult(entry.copy(fhirResourceId = written, dataSourceId = dataSourceId))+ repository.clearPending(MedicalKind.LabResult, id) }
health/src/main/java/com/vayunmathur/health/platform/MedicalImportOps.kt
diff --git a/health/src/main/java/com/vayunmathur/health/platform/MedicalImportOps.kt b/health/src/main/java/com/vayunmathur/health/platform/MedicalImportOps.ktindex 7d875768af..61e1eb6ab7 100644--- a/health/src/main/java/com/vayunmathur/health/platform/MedicalImportOps.kt+++ b/health/src/main/java/com/vayunmathur/health/platform/MedicalImportOps.kt@@ -3,17 +3,24 @@ package com.vayunmathur.health.platform import com.vayunmathur.library.log.Log import androidx.lifecycle.viewModelScope import com.vayunmathur.health.data.HealthProfile+import com.vayunmathur.health.data.MedicalKind+import com.vayunmathur.health.data.MedicationEntry+import com.vayunmathur.health.data.MedicationSchedule+import com.vayunmathur.health.data.MedicationStatus import com.vayunmathur.health.data.ProfileAnswer import com.vayunmathur.health.domain.FhirRecords import com.vayunmathur.health.domain.SocialHistoryQuestions import kotlinx.coroutines.launch+import java.util.UUID /**- * Pulls vaccinations and medications out of Health Connect into Room.+ * Brings Room and Health Connect into step: our own unsent changes go out, then everything+ * readable comes in. *- * This is what surfaces records a hospital or pharmacy has synced in, so it deliberately reads- * every data source rather than only this app's. Rows the app wrote are matched on their FHIR id- * and left alone; anything else is inserted.+ * Reading covers every data source, not only this app's, because that is what surfaces records a+ * hospital or pharmacy has synced in. Rows are matched on data source plus FHIR id, since FHIR+ * ids are only unique within one source. This app's own records are never overwritten by what it+ * reads back — Room is the source of truth for them — while a provider's are kept up to date. */ // Broad catch below is deliberate: provider-written FHIR is adversarial input — one // unparseable resource must not fail the whole import, and the Health Connect client@@ -24,8 +31,13 @@ fun MedicalViewModel.importFromHealthConnect() { viewModelScope.launch { syncingState.value = true try {- importVaccinesAndMeds()- importClinical()+ val own = PersonalHealthRecords.dataSourceId()+ if (own != null) {+ retryRemoteDeletes(own)+ pushPending()+ }+ importVaccinesAndMeds(own)+ importClinical(own) importProfile() } catch (e: Exception) { Log.error("MedicalViewModel", "Import from Health Connect failed", e)@@ -35,59 +47,238 @@ fun MedicalViewModel.importFromHealthConnect() { } } -private suspend fun MedicalViewModel.importVaccinesAndMeds() {- val vaccines = PersonalHealthRecords.readAll(PersonalHealthRecords.vaccinesType)- .mapNotNull { resource ->- FhirRecords.parseImmunization(resource.data, resource.dataSourceId)+private suspend fun MedicalViewModel.retryRemoteDeletes(own: String) {+ repository.getPendingRemoteDeletes(own).forEach { tombstone ->+ if (PersonalHealthRecords.delete(own, tombstone.fhirResourceType, tombstone.fhirResourceId)) {+ repository.upsertTombstone(tombstone.copy(retryDelete = false)) }- if (vaccines.isNotEmpty()) repository.upsertVaccinations(vaccines)-- // Medications are MedicationRequests; a MedicationStatement in the same category is- // a dose that was taken. Old records written by an earlier build are plain- // statements with no basedOn, so they parse as neither and are skipped rather than- // being misread as doses.- val medResources = PersonalHealthRecords.readAll(PersonalHealthRecords.medicationsType)+ }+} - val meds = medResources.mapNotNull { resource ->- FhirRecords.parseMedicationRequest(resource.data, resource.dataSourceId)+private suspend fun MedicalViewModel.pushPending() {+ repository.getPendingMirrors().forEach { pending ->+ when (pending.kind) {+ MedicalKind.Medication -> repository.mirrorMedication(pending.rowId)+ MedicalKind.Dose -> repository.mirrorDose(pending.rowId)+ MedicalKind.Vaccination -> mirrorVaccination(pending.rowId)+ MedicalKind.Allergy -> mirrorAllergy(pending.rowId)+ MedicalKind.Condition -> mirrorCondition(pending.rowId)+ MedicalKind.LabResult -> mirrorLabResult(pending.rowId)+ } }- if (meds.isNotEmpty()) {- meds.forEach { (entry, schedule) ->- // Room is the source of truth: a row this app wrote (same id already stored) is- // left alone, so reading back its own Health Connect mirror cannot clobber local- // state — including flipping an enabled reminder schedule back to disabled, which- // would otherwise happen on every import since parsed schedules arrive disabled.- if (repository.getMedication(entry.id) != null) return@forEach- repository.upsertMedication(entry)- // An imported schedule arrives disabled, so this cannot start alarms on its own.- schedule?.let { repository.upsertSchedule(it) }+}++/**+ * The local row id for a resource imported from another app's data source.+ *+ * Derived rather than random so the same resource always maps to the same row, and never the+ * bare FHIR id, which two sources can both use.+ */+private fun importedRowId(dataSourceId: String, fhirId: String): String =+ UUID.nameUUIDFromBytes("$dataSourceId/$fhirId".toByteArray()).toString()++/**+ * Applies one category of Health Connect resources to Room.+ *+ * For each resource: skipped if the user deleted it here; skipped if it is this app's own and+ * already stored; the local row removed if the author has retracted it; otherwise inserted, or+ * for a provider's record, updated in place under its existing row id.+ */+@Suppress("LongParameterList")+private suspend fun <Row : Any, Parsed : Any> MedicalViewModel.reconcile(+ kind: MedicalKind,+ resources: List<PersonalHealthRecords.RawResource>,+ own: String?,+ find: suspend (dataSourceId: String, fhirId: String) -> Row?,+ getById: suspend (rowId: String) -> Row?,+ rowIdOf: (Row) -> String,+ parse: (PersonalHealthRecords.RawResource) -> Parsed?,+ retract: suspend (Row) -> Unit,+ store: suspend (incoming: Parsed, rowId: String, existing: Row?) -> Unit,+) {+ resources.forEach { resource ->+ val source = resource.dataSourceId+ val fhirId = FhirRecords.resourceId(resource.data) ?: return@forEach+ if (repository.isTombstoned(kind, source, fhirId)) return@forEach+ val isOwn = source == own || PersonalHealthRecords.isOwnDataSource(source)+ val existing = find(source, fhirId)+ if (existing != null && isOwn) return@forEach++ if (FhirRecords.isEnteredInError(resource.data)) {+ existing?.let { retract(it) }+ return@forEach }+ val incoming = parse(resource) ?: return@forEach+ val rowId = existing?.let(rowIdOf) ?: if (isOwn) fhirId else importedRowId(source, fhirId)+ // Earlier builds used the bare FHIR id as the row id, and an edit could since have moved+ // such a row into this app's data source, where find() no longer matches it.+ if (existing == null && (getById(rowId) != null || getById(fhirId) != null)) return@forEach+ store(incoming, rowId, existing)+ }+}++private suspend fun MedicalViewModel.importVaccinesAndMeds(own: String?) {+ reconcile(+ kind = MedicalKind.Vaccination,+ resources = PersonalHealthRecords.readAll(PersonalHealthRecords.vaccinesType),+ own = own,+ find = repository::findVaccination,+ getById = repository::getVaccination,+ rowIdOf = { it.id },+ parse = { FhirRecords.parseImmunization(it.data, it.dataSourceId) },+ retract = { row ->+ repository.getAttachmentsFor(row.id).forEach { attachment ->+ AttachmentStore.delete(getApplication(), attachment.fileName)+ repository.deleteAttachment(attachment)+ }+ repository.deleteVaccination(row)+ },+ store = { incoming, rowId, _ -> repository.upsertVaccination(incoming.copy(id = rowId)) },+ )++ // Medications are MedicationRequests; a MedicationStatement in the same category is either a+ // dose taken against one of them, or a provider reporting a medication without a plan.+ val medResources = PersonalHealthRecords.readAll(PersonalHealthRecords.medicationsType)+ val (legacy, current) = medResources.partition { resource ->+ val isOwn = resource.dataSourceId == own || PersonalHealthRecords.isOwnDataSource(resource.dataSourceId)+ isOwn && FhirRecords.isUnplannedMedicationStatement(resource.data) }+ if (own != null) migrateLegacyStatements(legacy)++ reconcile(+ kind = MedicalKind.Medication,+ resources = current,+ own = own,+ find = repository::findMedication,+ getById = repository::getMedication,+ rowIdOf = { it.id },+ parse = { resource ->+ FhirRecords.parseMedicationRequest(resource.data, resource.dataSourceId)+ ?: FhirRecords.parseMedicationStatement(resource.data, resource.dataSourceId)+ ?.let { it to null }+ },+ retract = { row -> repository.deleteMedicationEverywhere(getApplication(), row) },+ store = { incoming, rowId, existing -> storeMedication(incoming, rowId, existing) },+ )++ reconcile(+ kind = MedicalKind.Dose,+ resources = current,+ own = own,+ find = repository::findDoseEvent,+ getById = repository::getDoseEvent,+ rowIdOf = { it.id },+ parse = { FhirRecords.parseDoseEvent(it.data, it.dataSourceId) },+ retract = { row -> repository.deleteDoseEvent(row) },+ store = { incoming, rowId, existing ->+ val medicationId = existing?.medicationId+ ?: resolveMedication(incoming.dataSourceId, incoming.medicationId)+ if (medicationId != null) {+ repository.upsertDoseEvent(incoming.copy(id = rowId, medicationId = medicationId))+ }+ },+ )+} - val doses = medResources.mapNotNull { resource ->- FhirRecords.parseDoseEvent(resource.data, resource.dataSourceId)+private suspend fun MedicalViewModel.storeMedication(+ incoming: Pair<MedicationEntry, MedicationSchedule?>,+ rowId: String,+ existing: MedicationEntry?,+) {+ val (entry, schedule) = incoming+ repository.upsertMedication(entry.copy(id = rowId))+ if (existing == null) {+ // An imported schedule arrives disabled, so this cannot start alarms on its own.+ schedule?.let { repository.upsertSchedule(it.copy(id = rowId, medicationId = rowId)) }+ } else if (entry.status != MedicationStatus.Active) {+ // The provider has stopped it, so whatever reminders the user turned on should stop too.+ repository.disableReminders(getApplication(), rowId) }- if (doses.isNotEmpty()) repository.upsertDoseEvents(doses) } -private suspend fun MedicalViewModel.importClinical() {- val allergyRows = PersonalHealthRecords.readAll(PersonalHealthRecords.allergiesType)- .mapNotNull { resource ->- FhirRecords.parseAllergyIntolerance(resource.data, resource.dataSourceId)- }- if (allergyRows.isNotEmpty()) repository.upsertAllergies(allergyRows)+/**+ * The local medication a dose's `basedOn` names.+ *+ * Looked up in the dose's own data source first, where a relative reference resolves. Failing+ * that, any source, but only when exactly one medication carries that id: a dose this app wrote+ * against a provider's request points across sources, and guessing between two would attach the+ * dose to the wrong medication.+ */+private suspend fun MedicalViewModel.resolveMedication(dataSourceId: String?, requestId: String): String? {+ dataSourceId?.let { repository.findMedication(it, requestId) }?.let { return it.id }+ return repository.findMedicationsByFhirId(requestId).singleOrNull()?.id+} - val conditionRows = PersonalHealthRecords.readAll(PersonalHealthRecords.conditionsType)- .mapNotNull { resource ->- FhirRecords.parseCondition(resource.data, resource.dataSourceId)+/**+ * Replaces regimens an earlier build wrote as `MedicationStatement`s with `MedicationRequest`s.+ *+ * The request is written before the statement is deleted, so a failure part way leaves a+ * duplicate for the next sync to finish rather than no record at all.+ */+private suspend fun MedicalViewModel.migrateLegacyStatements(+ legacy: List<PersonalHealthRecords.RawResource>,+) {+ legacy.forEach { resource ->+ val fhirId = FhirRecords.resourceId(resource.data) ?: return@forEach+ val local = repository.findMedication(resource.dataSourceId, fhirId)+ val rowId = when {+ local != null -> local.id+ repository.isTombstoned(MedicalKind.Medication, resource.dataSourceId, fhirId) -> null+ else -> FhirRecords.parseMedicationStatement(resource.data, resource.dataSourceId)+ ?.let { parsed ->+ if (repository.getMedication(fhirId) != null) return@let null+ repository.upsertMedication(parsed.copy(id = fhirId))+ fhirId+ } }- if (conditionRows.isNotEmpty()) repository.upsertConditions(conditionRows)-- val labRows = PersonalHealthRecords.readAll(PersonalHealthRecords.labsType)- .mapNotNull { resource ->- FhirRecords.parseLabResult(resource.data, resource.dataSourceId)+ if (rowId != null) {+ repository.markPending(MedicalKind.Medication, rowId)+ if (!repository.mirrorMedication(rowId)) return@forEach }- if (labRows.isNotEmpty()) repository.upsertLabResults(labRows)+ PersonalHealthRecords.delete(+ resource.dataSourceId,+ PersonalHealthRecords.medicationStatementResourceType,+ fhirId,+ )+ }+}++private suspend fun MedicalViewModel.importClinical(own: String?) {+ reconcile(+ kind = MedicalKind.Allergy,+ resources = PersonalHealthRecords.readAll(PersonalHealthRecords.allergiesType),+ own = own,+ find = repository::findAllergy,+ getById = repository::getAllergy,+ rowIdOf = { it.id },+ parse = { FhirRecords.parseAllergyIntolerance(it.data, it.dataSourceId) },+ retract = { row -> repository.deleteAllergy(row) },+ store = { incoming, rowId, _ -> repository.upsertAllergy(incoming.copy(id = rowId)) },+ )++ reconcile(+ kind = MedicalKind.Condition,+ resources = PersonalHealthRecords.readAll(PersonalHealthRecords.conditionsType),+ own = own,+ find = repository::findCondition,+ getById = repository::getCondition,+ rowIdOf = { it.id },+ parse = { FhirRecords.parseCondition(it.data, it.dataSourceId) },+ retract = { row -> repository.deleteCondition(row) },+ store = { incoming, rowId, _ -> repository.upsertCondition(incoming.copy(id = rowId)) },+ )++ reconcile(+ kind = MedicalKind.LabResult,+ resources = PersonalHealthRecords.readAll(PersonalHealthRecords.labsType),+ own = own,+ find = repository::findLabResult,+ getById = repository::getLabResult,+ rowIdOf = { it.id },+ parse = { FhirRecords.parseLabResult(it.data, it.dataSourceId) },+ retract = { row -> repository.deleteLabResult(row) },+ store = { incoming, rowId, _ -> repository.upsertLabResult(incoming.copy(id = rowId)) },+ ) } /**
health/src/main/java/com/vayunmathur/health/platform/MedicalMedicationOps.kt
diff --git a/health/src/main/java/com/vayunmathur/health/platform/MedicalMedicationOps.kt b/health/src/main/java/com/vayunmathur/health/platform/MedicalMedicationOps.ktindex a1ce31df24..d1f2ba1f2b 100644--- a/health/src/main/java/com/vayunmathur/health/platform/MedicalMedicationOps.kt+++ b/health/src/main/java/com/vayunmathur/health/platform/MedicalMedicationOps.kt@@ -3,9 +3,10 @@ package com.vayunmathur.health.platform import android.content.Context import androidx.lifecycle.viewModelScope import com.vayunmathur.health.data.DoseEvent+import com.vayunmathur.health.data.MedicalKind import com.vayunmathur.health.data.MedicationEntry import com.vayunmathur.health.data.MedicationSchedule-import com.vayunmathur.health.domain.FhirRecords+import com.vayunmathur.health.data.MedicationStatus import kotlinx.coroutines.launch import java.time.Instant import kotlin.uuid.Uuid@@ -15,7 +16,14 @@ fun MedicalViewModel.saveMedicationDraft() { if (draft.ingredient.isBlank()) return viewModelScope.launch { val existing = draft.editingId?.let { repository.getMedication(it) }- val entry = (existing ?: MedicationEntry(+ val detached = repository.detachIfForeign(+ MedicalKind.Medication,+ PersonalHealthRecords.medicationRequestResourceType,+ existing?.dataSourceId,+ existing?.fhirResourceId,+ )+ val active = draft.status == MedicationStatus.Active+ val edited = (existing ?: MedicationEntry( id = Uuid.random().toString(), displayName = "", startedAt = Instant.now(),@@ -26,20 +34,25 @@ fun MedicalViewModel.saveMedicationDraft() { doseForm = draft.doseForm, status = draft.status, startedAt = draft.startedOn.toInstant(),- endedAt = draft.endedOn?.toInstant(),+ // The end field is hidden while Active, so a date left over from before would+ // otherwise be saved without the user seeing it.+ endedAt = if (active) null else draft.endedOn?.toInstant(), dosageText = draft.dosage.blankToNull(), note = draft.note.blankToNull(), )+ val entry = if (detached) edited.copy(fhirResourceId = null, dataSourceId = null) else edited repository.upsertMedication(entry) saveSchedule(draft, entry.id)- mirrorMedication(entry.id)+ repository.markPending(MedicalKind.Medication, entry.id)+ repository.mirrorMedication(entry.id) } } /** * Writes or clears the reminder schedule for [medicationId] and re-arms the alarm. *- * Always re-arms from the stored row rather than the draft, so what fires is what was saved.+ * Always re-arms from the stored row rather than the draft, so what fires is what was saved. A+ * medication that is no longer being taken keeps its schedule but switched off, so it stops ringing. */ private suspend fun MedicalViewModel.saveSchedule( draft: MedicalViewModel.MedicationDraft,@@ -54,7 +67,7 @@ private suspend fun MedicalViewModel.saveSchedule( val schedule = MedicationSchedule( id = draft.scheduleId ?: Uuid.random().toString(), medicationId = medicationId,- enabled = true,+ enabled = draft.status == MedicationStatus.Active, times = draft.times.sorted(), repeatUnit = draft.repeatUnit, interval = draft.interval.coerceAtLeast(1),@@ -68,83 +81,24 @@ private suspend fun MedicalViewModel.saveSchedule( fun MedicalViewModel.deleteMedication(entry: MedicationEntry) { viewModelScope.launch {- repository.getScheduleFor(entry.id)?.let {- DoseScheduler.cancel(getApplication(), it.id)- }- repository.deleteScheduleFor(entry.id)- // The doses go with the medication. Leaving them would strand rows pointing at a- // MedicationRequest that no longer exists.- repository.deleteDosesFor(entry.id)- repository.deleteMedication(entry)- val dataSourceId = entry.dataSourceId- val fhirId = entry.fhirResourceId- if (dataSourceId != null && fhirId != null) {- PersonalHealthRecords.delete(- dataSourceId,- PersonalHealthRecords.medicationRequestResourceType,- fhirId,- )- }+ repository.deleteMedicationEverywhere(getApplication(), entry) } } -/**- * Writes the medication to Health Connect as a `MedicationRequest`.- *- * The schedule goes with it, which is what puts the reminder times in the record as- * `dosageInstruction.timing.repeat` rather than leaving them as a private detail of this app.- */-private suspend fun MedicalViewModel.mirrorMedication(id: String) {- val dataSourceId = PersonalHealthRecords.dataSourceId() ?: return- val entry = repository.getMedication(id) ?: return- val schedule = repository.getScheduleFor(id)- val written = PersonalHealthRecords.upsert(- dataSourceId,- FhirRecords.medicationRequestJson(entry, schedule),- ) ?: return- repository.upsertMedication(- entry.copy(fhirResourceId = written, dataSourceId = dataSourceId)- )-}--/**- * Records that a dose was taken, now.- *- * Called from the reminder's Taken action and from the medication list. Only acknowledged doses- * are ever written — see [DoseEvent].- */+/** Records that a dose was taken, now. Called from the medication list. */ fun MedicalViewModel.recordDoseTaken(medicationId: String, takenAt: Instant = Instant.now()) {- viewModelScope.launch {- val event = DoseEvent(- id = Uuid.random().toString(),- medicationId = medicationId,- takenAt = takenAt,- )- repository.upsertDoseEvent(event)-- val dataSourceId = PersonalHealthRecords.dataSourceId() ?: return@launch- val medication = repository.getMedication(medicationId) ?: return@launch- val written = PersonalHealthRecords.upsert(- dataSourceId,- FhirRecords.doseEventJson(event, medication),- ) ?: return@launch- repository.upsertDoseEvent(- event.copy(fhirResourceId = written, dataSourceId = dataSourceId)- )- }+ viewModelScope.launch { repository.recordDose(medicationId, takenAt) } } fun MedicalViewModel.deleteDoseEvent(event: DoseEvent) { viewModelScope.launch { repository.deleteDoseEvent(event)- val dataSourceId = event.dataSourceId- val fhirId = event.fhirResourceId- if (dataSourceId != null && fhirId != null) {- PersonalHealthRecords.delete(- dataSourceId,- PersonalHealthRecords.medicationStatementResourceType,- fhirId,- )- }+ repository.forgetRow(+ MedicalKind.Dose,+ event.id,+ PersonalHealthRecords.medicationStatementResourceType,+ event.dataSourceId,+ event.fhirResourceId,+ ) } }
health/src/main/java/com/vayunmathur/health/platform/MedicalMirror.kt
diff --git a/health/src/main/java/com/vayunmathur/health/platform/MedicalMirror.kt b/health/src/main/java/com/vayunmathur/health/platform/MedicalMirror.ktnew file mode 100644index 0000000000..a2122519e0--- /dev/null+++ b/health/src/main/java/com/vayunmathur/health/platform/MedicalMirror.kt@@ -0,0 +1,189 @@+@file:OptIn(kotlin.uuid.ExperimentalUuidApi::class)++package com.vayunmathur.health.platform++import android.content.Context+import com.vayunmathur.health.data.DeletedMedicalResource+import com.vayunmathur.health.data.DoseEvent+import com.vayunmathur.health.data.HealthRepository+import com.vayunmathur.health.data.MedicalKind+import com.vayunmathur.health.data.MedicationEntry+import com.vayunmathur.health.domain.FhirRecords+import java.time.Duration+import java.time.Instant+import kotlin.uuid.Uuid++/*+ * Keeps Health Connect in step with Room for the medical tables, from the ViewModel and from+ * receivers alike.+ *+ * Every local write queues a PendingMirror and every successful mirror clears it, so anything that+ * could not be written — Health Connect unavailable, a rejected resource, an alarm that started a+ * process with no client — is retried by the next sync. Deletes leave a DeletedMedicalResource so+ * the next import cannot bring the record back.+ *+ * Health Connect only lets an app write to its own data source, so a provider's record is never+ * rewritten in place: editing one detaches the local row into this app's own record and tombstones+ * the provider's original.+ */++/** Whether [dataSourceId] belongs to another app, such as a provider or a pharmacy. */+internal fun isForeignSource(dataSourceId: String?): Boolean =+ dataSourceId != null && !PersonalHealthRecords.isOwnDataSource(dataSourceId)++/**+ * Detaches a provider's record before the user's edit is saved over it.+ *+ * Returns true when the row was foreign. The provider's original is tombstoned so imports stop+ * overwriting the edit, and the caller clears the row's FHIR columns so the next mirror writes it+ * into this app's data source as the user's own version.+ */+internal suspend fun HealthRepository.detachIfForeign(+ kind: MedicalKind,+ fhirResourceType: Int,+ dataSourceId: String?,+ fhirResourceId: String?,+): Boolean {+ if (dataSourceId == null || fhirResourceId == null || !isForeignSource(dataSourceId)) return false+ upsertTombstone(+ DeletedMedicalResource(kind, dataSourceId, fhirResourceId, fhirResourceType, retryDelete = false)+ )+ return true+}++/**+ * Forgets a row that has just been deleted locally, in Health Connect and in the bookkeeping.+ *+ * Always tombstoned: a provider's copy cannot be deleted by this app, and deleting our own can+ * fail. Our own copy is flagged for retry until a delete lands.+ */+internal suspend fun HealthRepository.forgetRow(+ kind: MedicalKind,+ rowId: String,+ fhirResourceType: Int,+ dataSourceId: String?,+ fhirResourceId: String?,+) {+ clearPending(kind, rowId)+ if (dataSourceId == null || fhirResourceId == null) return+ val settled = isForeignSource(dataSourceId) ||+ PersonalHealthRecords.delete(dataSourceId, fhirResourceType, fhirResourceId)+ upsertTombstone(+ DeletedMedicalResource(kind, dataSourceId, fhirResourceId, fhirResourceType, retryDelete = !settled)+ )+}++/**+ * The data source to mirror a row into, or null when it should not be written now.+ *+ * Null when Health Connect is unavailable, in which case the row stays queued, or when the row is+ * a provider's and so not this app's to write, in which case the queue entry is dropped.+ */+internal suspend fun HealthRepository.mirrorTarget(+ kind: MedicalKind,+ rowId: String,+ rowDataSourceId: String?,+): String? {+ if (isForeignSource(rowDataSourceId)) {+ clearPending(kind, rowId)+ return null+ }+ return PersonalHealthRecords.dataSourceId()+}++/**+ * Writes the medication to Health Connect as a `MedicationRequest`.+ *+ * The schedule goes with it, which is what puts the reminder times in the record as+ * `dosageInstruction.timing.repeat` rather than leaving them as a private detail of this app.+ */+internal suspend fun HealthRepository.mirrorMedication(id: String): Boolean {+ val entry = getMedication(id) ?: run {+ clearPending(MedicalKind.Medication, id)+ return false+ }+ val target = mirrorTarget(MedicalKind.Medication, id, entry.dataSourceId) ?: return false+ val written = PersonalHealthRecords.upsert(+ target,+ FhirRecords.medicationRequestJson(entry, getScheduleFor(id)),+ ) ?: return false+ upsertMedication(entry.copy(fhirResourceId = written, dataSourceId = target))+ clearPending(MedicalKind.Medication, id)+ return true+}++/** Writes a dose as a `MedicationStatement`, mirroring its medication first if that never landed. */+internal suspend fun HealthRepository.mirrorDose(id: String): Boolean {+ val event = getDoseEvent(id) ?: run {+ clearPending(MedicalKind.Dose, id)+ return false+ }+ val target = mirrorTarget(MedicalKind.Dose, id, event.dataSourceId) ?: return false+ // basedOn must point at a MedicationRequest that actually exists in Health Connect.+ val unmirrored = getMedication(event.medicationId) ?: return false+ if (unmirrored.fhirResourceId == null && !mirrorMedication(unmirrored.id)) return false+ val medication = getMedication(event.medicationId) ?: return false++ val written = PersonalHealthRecords.upsert(+ target,+ FhirRecords.doseEventJson(event, medication),+ ) ?: return false+ upsertDoseEvent(event.copy(fhirResourceId = written, dataSourceId = target))+ clearPending(MedicalKind.Dose, id)+ return true+}++/** Two taps this close together are one dose recorded twice, from the reminder and the list. */+private val DUPLICATE_DOSE_WINDOW: Duration = Duration.ofMinutes(5)++/**+ * Records that a dose was taken: locally first, then mirrored.+ *+ * Only acknowledged doses are ever written — see [DoseEvent].+ */+internal suspend fun HealthRepository.recordDose(medicationId: String, takenAt: Instant = Instant.now()) {+ val last = getRecentDoses(medicationId, 1).firstOrNull()+ if (last != null && Duration.between(last.takenAt, takenAt).abs() < DUPLICATE_DOSE_WINDOW) return++ val event = DoseEvent(id = Uuid.random().toString(), medicationId = medicationId, takenAt = takenAt)+ upsertDoseEvent(event)+ markPending(MedicalKind.Dose, event.id)+ mirrorDose(event.id)+}++/**+ * Deletes a medication with its schedule and doses, here and in Health Connect.+ *+ * The doses go with it. Leaving them would strand statements pointing at a MedicationRequest that+ * no longer exists, and the next import would read them back as orphan rows.+ */+internal suspend fun HealthRepository.deleteMedicationEverywhere(context: Context, entry: MedicationEntry) {+ getScheduleFor(entry.id)?.let { DoseScheduler.cancel(context, it.id) }+ deleteScheduleFor(entry.id)+ val doses = getDosesFor(entry.id)+ deleteDosesFor(entry.id)+ deleteMedication(entry)+ doses.forEach { dose ->+ forgetRow(+ MedicalKind.Dose,+ dose.id,+ PersonalHealthRecords.medicationStatementResourceType,+ dose.dataSourceId,+ dose.fhirResourceId,+ )+ }+ forgetRow(+ MedicalKind.Medication,+ entry.id,+ PersonalHealthRecords.medicationRequestResourceType,+ entry.dataSourceId,+ entry.fhirResourceId,+ )+}++/** Turns a medication's reminders off without discarding the schedule itself. */+internal suspend fun HealthRepository.disableReminders(context: Context, medicationId: String) {+ val schedule = getScheduleFor(medicationId) ?: return+ DoseScheduler.cancel(context, schedule.id)+ if (schedule.enabled) upsertSchedule(schedule.copy(enabled = false))+}
health/src/main/java/com/vayunmathur/health/platform/MedicalVaccinationOps.kt
diff --git a/health/src/main/java/com/vayunmathur/health/platform/MedicalVaccinationOps.kt b/health/src/main/java/com/vayunmathur/health/platform/MedicalVaccinationOps.ktindex 9cc4ed31d8..5e20aa6b97 100644--- a/health/src/main/java/com/vayunmathur/health/platform/MedicalVaccinationOps.kt+++ b/health/src/main/java/com/vayunmathur/health/platform/MedicalVaccinationOps.kt@@ -3,6 +3,7 @@ package com.vayunmathur.health.platform import androidx.core.net.toUri import androidx.lifecycle.viewModelScope import com.vayunmathur.health.data.MedicalAttachment+import com.vayunmathur.health.data.MedicalKind import com.vayunmathur.health.data.VaccinationEntry import com.vayunmathur.health.domain.FhirRecords import kotlinx.coroutines.Dispatchers@@ -25,9 +26,15 @@ fun MedicalViewModel.saveVaccinationDraft(fallbackAttachmentName: String) { viewModelScope.launch { // Keeping the row id on edit is what makes the Health Connect mirror an update rather- // than a second resource, since the row id is also the FHIR resource id.+ // than a second resource. A provider's record is detached into the user's own instead. val existing = draft.editingId?.let { repository.getVaccination(it) }- val entry = (existing ?: VaccinationEntry(+ val detached = repository.detachIfForeign(+ MedicalKind.Vaccination,+ PersonalHealthRecords.immunizationResourceType,+ existing?.dataSourceId,+ existing?.fhirResourceId,+ )+ val edited = (existing ?: VaccinationEntry( id = Uuid.random().toString(), displayName = "", occurredAt = Instant.now(),@@ -42,7 +49,9 @@ fun MedicalViewModel.saveVaccinationDraft(fallbackAttachmentName: String) { performer = draft.performer.blankToNull(), note = draft.note.blankToNull(), )+ val entry = if (detached) edited.copy(fhirResourceId = null, dataSourceId = null) else edited repository.upsertVaccination(entry)+ repository.markPending(MedicalKind.Vaccination, entry.id) draft.savedAttachments .filter { it.id in draft.removedAttachmentIds }@@ -82,22 +91,20 @@ fun MedicalViewModel.deleteVaccination(entry: VaccinationEntry) { repository.deleteAttachment(attachment) } repository.deleteVaccination(entry)-- val dataSourceId = entry.dataSourceId- val fhirId = entry.fhirResourceId- if (dataSourceId != null && fhirId != null) {- PersonalHealthRecords.delete(- dataSourceId,- PersonalHealthRecords.immunizationResourceType,- fhirId,- )- }+ repository.forgetRow(+ MedicalKind.Vaccination,+ entry.id,+ PersonalHealthRecords.immunizationResourceType,+ entry.dataSourceId,+ entry.fhirResourceId,+ ) } } -private suspend fun MedicalViewModel.mirrorVaccination(id: String) {- val dataSourceId = PersonalHealthRecords.dataSourceId() ?: return- val entry = repository.getVaccination(id) ?: return+internal suspend fun MedicalViewModel.mirrorVaccination(id: String) {+ val entry = repository.getVaccination(id)+ ?: return repository.clearPending(MedicalKind.Vaccination, id)+ val dataSourceId = repository.mirrorTarget(MedicalKind.Vaccination, id, entry.dataSourceId) ?: return val fhirAttachments = repository.getAttachmentsFor(id).map { attachment -> FhirRecords.FhirAttachment( contentType = attachment.mimeType,@@ -113,4 +120,5 @@ private suspend fun MedicalViewModel.mirrorVaccination(id: String) { repository.upsertVaccination( entry.copy(fhirResourceId = written, dataSourceId = dataSourceId) )+ repository.clearPending(MedicalKind.Vaccination, id) }
health/src/main/java/com/vayunmathur/health/platform/MedicalViewModel.kt
diff --git a/health/src/main/java/com/vayunmathur/health/platform/MedicalViewModel.kt b/health/src/main/java/com/vayunmathur/health/platform/MedicalViewModel.ktindex a1c2cbb7b8..506c423a98 100644--- a/health/src/main/java/com/vayunmathur/health/platform/MedicalViewModel.kt+++ b/health/src/main/java/com/vayunmathur/health/platform/MedicalViewModel.kt@@ -64,7 +64,7 @@ internal fun String.blankToNull(): String? = trim().ifBlank { null } * Room is the source of truth and Health Connect is a mirror written afterwards. That ordering is * what makes the feature work at all below Android 15, where the Personal Health Record API does not * exist, and it means a rejected or failed FHIR write costs the user nothing — the row is already- * saved, it simply has no `fhirResourceId` yet.+ * saved and stays queued in `PendingMirror` until a sync gets it written. * * The save/delete/mirror/import operations live in same-package files * ([MedicalVaccinationOps.kt][saveVaccinationDraft], [MedicalMedicationOps.kt][saveMedicationDraft],@@ -371,7 +371,10 @@ class MedicalViewModel( dosage = entry.dosageText.orEmpty(), note = entry.note.orEmpty(), scheduleId = schedule?.id,- remindersEnabled = schedule?.enabled == true,+ // A stopped medication's schedule is kept but switched off; showing it as on is+ // what lets reactivating the medication bring its reminders back.+ remindersEnabled = schedule != null &&+ (schedule.enabled || entry.status != MedicationStatus.Active), times = schedule?.times?.takeIf { it.isNotEmpty() } ?: listOf(DEFAULT_DOSE_TIME_SECONDS), repeatUnit = schedule?.repeatUnit ?: RepeatUnit.Daily,
health/src/main/java/com/vayunmathur/health/platform/PersonalHealthRecords.kt
diff --git a/health/src/main/java/com/vayunmathur/health/platform/PersonalHealthRecords.kt b/health/src/main/java/com/vayunmathur/health/platform/PersonalHealthRecords.ktindex 4e481c6105..86d9128084 100644--- a/health/src/main/java/com/vayunmathur/health/platform/PersonalHealthRecords.kt+++ b/health/src/main/java/com/vayunmathur/health/platform/PersonalHealthRecords.kt@@ -34,7 +34,8 @@ import kotlinx.coroutines.sync.withLock * devices in the supported range. * * Every write also tolerates failure at runtime. A rejected resource must not cost the user the entry- * they just typed, so failures are logged and swallowed and the Room row simply stays unmirrored.+ * they just typed, so failures are logged and swallowed; the row stays queued in `PendingMirror` and+ * the next sync retries it. */ object PersonalHealthRecords { @@ -65,6 +66,7 @@ object PersonalHealthRecords { /** Key in the existing `"sync"` SharedPreferences that `HealthAPI` owns. */ private const val PREF_DATA_SOURCE_ID = "phr_data_source_id"+ private const val PREF_OWNED_DATA_SOURCE_IDS = "phr_owned_data_source_ids" private const val DATA_SOURCE_DISPLAY_NAME = "MA Health" private val DATA_SOURCE_URI: Uri = "https://maproj.org/fhir/ma-health".toUri()@@ -72,24 +74,46 @@ object PersonalHealthRecords { /** Serialises get-or-create so two screens opening at once cannot create two data sources. */ private val dataSourceMutex = Mutex() - private lateinit var appContext: Context- private lateinit var client: HealthConnectClient+ @Volatile private var appContext: Context? = null+ @Volatile private var client: HealthConnectClient? = null++ private val hc: HealthConnectClient get() = checkNotNull(client) fun init(context: Context, healthConnectClient: HealthConnectClient) { appContext = context.applicationContext client = healthConnectClient } + /**+ * Sets up the client for an entry point that runs without `MainActivity`, such as a dose+ * alarm's Taken action in a process the alarm just started.+ */+ // Broad catch is deliberate: getOrCreate throws when Health Connect is missing or+ // unsupported, and that has to leave the feature unavailable rather than crash a receiver.+ @Suppress("TooGenericExceptionCaught")+ fun ensureInitialized(context: Context) {+ if (client != null) return+ appContext = context.applicationContext+ try {+ init(context, HealthConnectClient.getOrCreate(context.applicationContext))+ } catch (e: Exception) {+ Log.status(TAG, "Health Connect is not available to initialise", e)+ }+ }+ // Broad catch is deliberate: this is the availability probe whose contract is to // never throw, and the Health Connect client throws undocumented RuntimeExceptions // (not just declared ones) when the module is missing or outdated. @Suppress("TooGenericExceptionCaught")- fun isAvailable(): Boolean = try {- client.features.getFeatureStatus(HealthConnectFeatures.FEATURE_PERSONAL_HEALTH_RECORD) ==- HealthConnectFeatures.FEATURE_STATUS_AVAILABLE- } catch (e: Exception) {- Log.status(TAG, "Could not query the Personal Health Record feature status", e)- false+ fun isAvailable(): Boolean {+ val current = client ?: return false+ return try {+ current.features.getFeatureStatus(HealthConnectFeatures.FEATURE_PERSONAL_HEALTH_RECORD) ==+ HealthConnectFeatures.FEATURE_STATUS_AVAILABLE+ } catch (e: Exception) {+ Log.status(TAG, "Could not query the Personal Health Record feature status", e)+ false+ } } /**@@ -100,22 +124,22 @@ object PersonalHealthRecords { * stale cached id would make every subsequent write fail. */ // Broad catch is deliberate: a rejected data source must not cost the user the entry- // they just typed — the Room row simply stays unmirrored and a later import reconciles.+ // they just typed — the row stays queued and the next sync retries it. // The Health Connect client throws undocumented RuntimeExceptions, not just declared ones. @Suppress("TooGenericExceptionCaught") suspend fun dataSourceId(): String? { if (!isAvailable()) return null return dataSourceMutex.withLock { try {- val existing = client- .getMedicalDataSources(GetMedicalDataSourcesRequest(listOf(appContext.packageName)))+ val existing = hc+ .getMedicalDataSources(GetMedicalDataSourcesRequest(listOf(checkNotNull(appContext).packageName))) .firstOrNull() if (existing != null) { cacheDataSourceId(existing.id) return@withLock existing.id } - val created = client.createMedicalDataSource(+ val created = hc.createMedicalDataSource( CreateMedicalDataSourceRequest( fhirBaseUri = DATA_SOURCE_URI, displayName = DATA_SOURCE_DISPLAY_NAME,@@ -134,17 +158,35 @@ object PersonalHealthRecords { } } + private fun prefs() = appContext?.getSharedPreferences("sync", Context.MODE_PRIVATE)+ private fun cacheDataSourceId(id: String) {- appContext.getSharedPreferences("sync", Context.MODE_PRIVATE)- .edit { putString(PREF_DATA_SOURCE_ID, id) }+ val prefs = prefs() ?: return+ val owned = prefs.getStringSet(PREF_OWNED_DATA_SOURCE_IDS, null).orEmpty()+ prefs.edit {+ putString(PREF_DATA_SOURCE_ID, id)+ putStringSet(PREF_OWNED_DATA_SOURCE_IDS, owned + id)+ }+ }++ /**+ * Whether [dataSourceId] is, or once was, this app's own.+ *+ * Once rather than only now: the user can delete the data source from Health Connect's+ * settings, and rows written to the old one are still this app's to rewrite into the new one.+ */+ fun isOwnDataSource(dataSourceId: String): Boolean {+ val prefs = prefs() ?: return false+ return dataSourceId == prefs.getString(PREF_DATA_SOURCE_ID, null) ||+ dataSourceId in prefs.getStringSet(PREF_OWNED_DATA_SOURCE_IDS, null).orEmpty() } /** Writes one FHIR resource, returning its Health Connect id or null if the write did not land. */ // Broad catch is deliberate: a rejected resource must not cost the user the entry they- // just typed, so failures are logged and swallowed and the Room row stays unmirrored.+ // just typed, so failures are logged and swallowed and the row stays queued for retry. @Suppress("TooGenericExceptionCaught") suspend fun upsert(dataSourceId: String, data: String): String? = try {- client.upsertMedicalResources(+ hc.upsertMedicalResources( listOf(UpsertMedicalResourceRequest(dataSourceId, FHIR_VERSION, data)) ).firstOrNull()?.id?.fhirResourceId } catch (e: Exception) {@@ -152,17 +194,20 @@ object PersonalHealthRecords { null } - // Broad catch is deliberate: delete is best-effort cleanup — a stale mirror row is- // harmless next to a crash, and the client throws undocumented RuntimeExceptions.+ /** Deletes one of this app's resources, returning whether Health Connect confirmed it. */+ // Broad catch is deliberate: a failed delete is recorded and retried on the next sync,+ // and the client throws undocumented RuntimeExceptions. @Suppress("TooGenericExceptionCaught")- suspend fun delete(dataSourceId: String, fhirResourceType: Int, fhirResourceId: String) {- if (!isAvailable()) return- try {- client.deleteMedicalResources(+ suspend fun delete(dataSourceId: String, fhirResourceType: Int, fhirResourceId: String): Boolean {+ if (!isAvailable()) return false+ return try {+ hc.deleteMedicalResources( listOf(MedicalResourceId(dataSourceId, fhirResourceType, fhirResourceId)) )+ true } catch (e: Exception) { Log.error(TAG, "Could not delete a medical resource", e)+ false } } @@ -188,13 +233,13 @@ object PersonalHealthRecords { if (!isAvailable()) return emptyList() return try { val all = mutableListOf<MedicalResource>()- var response = client.readMedicalResources(+ var response = hc.readMedicalResources( ReadMedicalResourcesInitialRequest(medicalResourceType, emptySet(), PAGE_SIZE) ) all += response.medicalResources var token = response.nextPageToken while (token != null) {- response = client.readMedicalResources(+ response = hc.readMedicalResources( ReadMedicalResourcesPageRequest(token, PAGE_SIZE) ) all += response.medicalResources
health/src/test/java/com/vayunmathur/health/domain/FhirRecordsTest.kt
diff --git a/health/src/test/java/com/vayunmathur/health/domain/FhirRecordsTest.kt b/health/src/test/java/com/vayunmathur/health/domain/FhirRecordsTest.ktindex 12fcd7fb3f..5cc05764e7 100644--- a/health/src/test/java/com/vayunmathur/health/domain/FhirRecordsTest.kt+++ b/health/src/test/java/com/vayunmathur/health/domain/FhirRecordsTest.kt@@ -22,8 +22,13 @@ import kotlinx.serialization.json.jsonArray import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive import java.time.Instant+import java.time.ZoneId+import java.util.TimeZone+import kotlin.test.AfterTest+import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals+import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue@@ -37,6 +42,21 @@ class FhirRecordsTest { private val json = Json + // Date-precision fields are written and read in the device's zone, so pin it: the fixtures+ // below use UTC midnight to stand for a picked date.+ private lateinit var originalZone: TimeZone++ @BeforeTest+ fun pinZone() {+ originalZone = TimeZone.getDefault()+ TimeZone.setDefault(TimeZone.getTimeZone("UTC"))+ }++ @AfterTest+ fun restoreZone() {+ TimeZone.setDefault(originalZone)+ }+ private fun parse(text: String): JsonObject = json.parseToJsonElement(text).jsonObject private fun JsonObject.str(key: String): String? = this[key]?.jsonPrimitive?.content@@ -175,7 +195,8 @@ class FhirRecordsTest { assertEquals(FhirRecords.RXNORM_SYSTEM, coding.str("system")) assertEquals("308182", coding.str("code")) assertEquals("amoxicillin 250 MG Oral Capsule", coding.str("display"))- assertEquals("2026-01-10T00:00:00Z", root.str("authoredOn"))+ // A picked date travels as a date, not as a UTC instant that can land on another day.+ assertEquals("2026-01-10", root.str("authoredOn")) } @Test@@ -195,9 +216,36 @@ class FhirRecordsTest { assertEquals(amoxicillin.rxcui, parsed.rxcui) assertEquals(amoxicillin.status, parsed.status) assertEquals(amoxicillin.startedAt, parsed.startedAt)+ assertEquals(amoxicillin.endedAt, parsed.endedAt) assertEquals(amoxicillin.dosageText, parsed.dosageText) } + @Test+ fun `a finished course keeps its end date even without reminders`() {+ val root = parse(FhirRecords.medicationRequestJson(amoxicillin))+ val bounds = root["dosageInstruction"]!!.jsonArray.single().jsonObject["timing"]!!+ .jsonObject["repeat"]!!.jsonObject["boundsPeriod"]!!.jsonObject++ assertEquals("2026-01-10", bounds.str("start"))+ assertEquals("2026-01-17", bounds.str("end"))+ }++ @Test+ fun `an ongoing course does not carry a stale end date`() {+ val ongoing = amoxicillin.copy(status = MedicationStatus.Active)+ val root = parse(FhirRecords.medicationRequestJson(ongoing))+ val bounds = root["dosageInstruction"]!!.jsonArray.single().jsonObject["timing"]!!+ .jsonObject["repeat"]!!.jsonObject["boundsPeriod"]!!.jsonObject++ assertNull(bounds.str("end"))+ }++ @Test+ fun `the FHIR id is kept when the row already has one`() {+ val imported = amoxicillin.copy(id = "local-row", fhirResourceId = "fhir-7")+ assertEquals("fhir-7", parse(FhirRecords.medicationRequestJson(imported)).str("id"))+ }+ @Test fun `the dose schedule travels as timing repeat`() { val schedule = MedicationSchedule(@@ -211,7 +259,8 @@ class FhirRecordsTest { anchorDate = KotlinLocalDate(2026, 1, 10), endDate = KotlinLocalDate(2026, 3, 1), )- val dosage = parse(FhirRecords.medicationRequestJson(amoxicillin, schedule))[+ val ongoing = amoxicillin.copy(status = MedicationStatus.Active, endedAt = null)+ val dosage = parse(FhirRecords.medicationRequestJson(ongoing, schedule))[ "dosageInstruction" ]!!.jsonArray.single().jsonObject val repeat = dosage["timing"]!!.jsonObject["repeat"]!!.jsonObject@@ -222,7 +271,8 @@ class FhirRecordsTest { ) assertEquals("2", repeat.str("period")) assertEquals("wk", repeat.str("periodUnit"))- assertEquals("2", repeat.str("frequency"))+ // Doses per period: two times of day on each of two days.+ assertEquals("4", repeat.str("frequency")) assertEquals( listOf("mon", "thu"), (repeat["dayOfWeek"] as JsonArray).map { it.jsonPrimitive.content },@@ -264,6 +314,79 @@ class FhirRecordsTest { assertNull(parsed.second) } + private fun requestWithRepeat(repeat: String) = """+ {+ "resourceType": "MedicationRequest",+ "id": "rx-1",+ "status": "active",+ "intent": "order",+ "medicationCodeableConcept": { "text": "Ibuprofen" },+ "subject": { "reference": "Patient/other" },+ "dosageInstruction": [ { "timing": { "repeat": $repeat } } ]+ }+ """.trimIndent()++ @Test+ fun `an hourly regimen is not read as a daily one`() {+ val parsed = FhirRecords.parseMedicationRequest(+ requestWithRepeat(+ """{ "boundsPeriod": { "start": "2026-02-01" }, "timeOfDay": ["08:00:00"],+ "period": 8, "periodUnit": "h" }"""+ ),+ "hospital",+ )++ assertNotNull(parsed)+ assertNull(parsed.second)+ }++ @Test+ fun `daily on chosen weekdays becomes weekly on those days`() {+ val schedule = FhirRecords.parseMedicationRequest(+ requestWithRepeat(+ """{ "boundsPeriod": { "start": "2026-02-01" }, "timeOfDay": ["08:00:00"],+ "period": 1, "periodUnit": "d", "dayOfWeek": ["mon", "wed", "fri"] }"""+ ),+ "hospital",+ )?.second++ assertNotNull(schedule)+ assertEquals(RepeatUnit.Weekly, schedule.repeatUnit)+ assertEquals(1, schedule.interval)+ assertEquals((1 shl 1) or (1 shl 3) or (1 shl 5), schedule.daysOfWeek)+ }++ @Test+ fun `a course start comes from the dosing period rather than when it was written`() {+ val provider = """+ {+ "resourceType": "MedicationRequest",+ "id": "rx-2",+ "status": "active",+ "intent": "order",+ "medicationCodeableConcept": { "text": "Metformin" },+ "subject": { "reference": "Patient/other" },+ "authoredOn": "2026-01-20",+ "dosageInstruction": [ { "timing": { "repeat": { "boundsPeriod": { "start": "2026-02-01" } } } } ]+ }+ """.trimIndent()++ val parsed = FhirRecords.parseMedicationRequest(provider, "hospital")?.first++ assertNotNull(parsed)+ assertEquals(Instant.parse("2026-02-01T00:00:00Z"), parsed.startedAt)+ }++ @Test+ fun `a retracted request is not a medication`() {+ val retracted = FhirRecords.medicationRequestJson(amoxicillin)+ .replace("\"status\":\"completed\"", "\"status\":\"entered-in-error\"")++ assertTrue(FhirRecords.isEnteredInError(retracted))+ assertNull(FhirRecords.parseMedicationRequest(retracted, "src"))+ assertFalse(FhirRecords.isEnteredInError(FhirRecords.medicationRequestJson(amoxicillin)))+ }+ // --- MedicationStatement: the dose actually taken -------------------------- @Test@@ -286,6 +409,46 @@ class FhirRecordsTest { ) } + @Test+ fun `a dose points at the plan's FHIR id, not its local row id`() {+ val imported = amoxicillin.copy(id = "local-row", fhirResourceId = "fhir-7")+ val event = DoseEvent("dose-1", imported.id, Instant.parse("2026-01-12T08:05:00Z"))+ val root = parse(FhirRecords.doseEventJson(event, imported))++ assertEquals(+ "MedicationRequest/fhir-7",+ (root["basedOn"] as JsonArray).single().jsonObject.str("reference"),+ )+ }++ @Test+ fun `only a completed statement is a dose taken`() {+ val event = DoseEvent("dose-1", amoxicillin.id, Instant.parse("2026-01-12T08:05:00Z"))+ val taken = FhirRecords.doseEventJson(event, amoxicillin)++ listOf("not-taken", "intended", "active", "entered-in-error").forEach { status ->+ val other = taken.replace("\"status\":\"completed\"", "\"status\":\"$status\"")+ assertNull(FhirRecords.parseDoseEvent(other, "src"), status)+ }+ }++ @Test+ fun `an absolute basedOn reference still finds its plan`() {+ val provider = """+ {+ "resourceType": "MedicationStatement",+ "id": "dose-9",+ "status": "completed",+ "basedOn": [ { "reference": "https://fhir.example.org/MedicationRequest/rx-4/_history/2" } ],+ "medicationCodeableConcept": { "text": "Metformin" },+ "subject": { "reference": "Patient/other" },+ "effectiveDateTime": "2026-01-12T08:05:00Z"+ }+ """.trimIndent()++ assertEquals("rx-4", FhirRecords.parseDoseEvent(provider, "hospital")?.medicationId)+ }+ @Test fun `a dose round trips`() { val event = DoseEvent(@@ -331,6 +494,38 @@ class FhirRecordsTest { assertNull(FhirRecords.parseDoseEvent(bare, "hospital")) } + @Test+ fun `a provider's reported medication is read as a medication`() {+ val reported = """+ {+ "resourceType": "MedicationStatement",+ "id": "reported-1",+ "status": "completed",+ "medicationCodeableConcept": { "text": "Metformin" },+ "subject": { "reference": "Patient/other" },+ "effectivePeriod": { "start": "2024-06-01", "end": "2024-09-01" }+ }+ """.trimIndent()++ assertTrue(FhirRecords.isUnplannedMedicationStatement(reported))+ val parsed = FhirRecords.parseMedicationStatement(reported, "hospital")++ assertNotNull(parsed)+ assertEquals("Metformin", parsed.displayName)+ assertEquals(MedicationStatus.Completed, parsed.status)+ assertEquals(Instant.parse("2024-06-01T00:00:00Z"), parsed.startedAt)+ assertEquals(Instant.parse("2024-09-01T00:00:00Z"), parsed.endedAt)+ }++ @Test+ fun `a dose is never read as a reported medication`() {+ val event = DoseEvent("dose-1", amoxicillin.id, Instant.parse("2026-01-12T08:05:00Z"))+ val dose = FhirRecords.doseEventJson(event, amoxicillin)++ assertFalse(FhirRecords.isUnplannedMedicationStatement(dose))+ assertNull(FhirRecords.parseMedicationStatement(dose, "src"))+ }+ // --- Reading what other systems write ------------------------------------ @Test@@ -494,7 +689,7 @@ class FhirRecordsTest { "problem-list-item", category["coding"]!!.jsonArray.single().jsonObject.str("code"), )- assertEquals("2022-01-15T00:00:00Z", root.str("onsetDateTime"))+ assertEquals("2022-01-15", root.str("onsetDateTime")) val coding = root["code"]!!.jsonObject["coding"]!!.jsonArray.single().jsonObject assertEquals(FhirRecords.ICD10_SYSTEM, coding.str("system"))@@ -513,7 +708,7 @@ class FhirRecordsTest { "resolved", root["clinicalStatus"]!!.jsonObject["coding"]!!.jsonArray.single().jsonObject.str("code"), )- assertEquals("2024-08-01T00:00:00Z", root.str("abatementDateTime"))+ assertEquals("2024-08-01", root.str("abatementDateTime")) } @Test@@ -653,7 +848,7 @@ class FhirRecordsTest { assertEquals("77386006", value.str("code")) val component = (root["component"] as JsonArray).single().jsonObject- assertEquals("2026-11-01T00:00:00Z", component.str("valueDateTime"))+ assertEquals("2026-11-01", component.str("valueDateTime")) val (status, due) = FhirRecords.parsePregnancyStatus(json)!! assertEquals(PregnancyStatus.Pregnant, status)@@ -738,4 +933,22 @@ class FhirRecordsTest { assertNull(FhirRecords.parseDateTime("not a date")) assertNull(FhirRecords.parseDateTime(null)) }++ @Test+ fun `a date-only value lands on that day in the device's zone`() {+ val pacific = ZoneId.of("America/Los_Angeles")+ val parsed = FhirRecords.parseDateTime("2026-03-04", pacific)++ assertNotNull(parsed)+ assertEquals(java.time.LocalDate.of(2026, 3, 4), parsed.atZone(pacific).toLocalDate())+ }++ @Test+ fun `a picked date is written as a date in any zone`() {+ val tokyo = ZoneId.of("Asia/Tokyo")+ val midnight = java.time.LocalDate.of(2026, 3, 4).atStartOfDay(tokyo).toInstant()++ assertEquals("2026-03-04", formatClinicalDate(midnight, tokyo))+ assertEquals("2026-03-04T09:30:00Z", formatClinicalDate(Instant.parse("2026-03-04T09:30:00Z"), tokyo))+ } }