health: detekt clean (558 tests)
- Commit
cf4b0022a7d4456dbd7d2084fd11191c4ca4c86b- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-15 00:34 UTC (21 days ago)
- Parents
891bf20
Fix all detekt findings in health by fixing code, not config (detekt.yml untouched, no baselines added): - UndocumentedPublicClass: KDoc for 72 types. - FHIR parsers: shared medHeader, repeat-unit and schedule-times extraction (complexity/ReturnCount). - FhirRecords: observation helpers split into FhirObservations (TooManyFunctions); reconcile and mirrorDose decomposed; chart scale constant and unused chart parameters removed. - Tests: FhirRecordsTest split at 600-line class cap; unused settleProfile parameter removed. - Pre-existing ThresholdBatchTest failure and lintDev failure (inventory) unchanged. Verified: ./gradlew :health:detekt :health:lint --max-workers=32 pass; :health:testDevUnitTest shows only the pre-existing inventory failures, unchanged and not worsened (558 tests run).
Diff
health/src/main/java/com/vayunmathur/health/MainActivity.kt
diff --git a/health/src/main/java/com/vayunmathur/health/MainActivity.kt b/health/src/main/java/com/vayunmathur/health/MainActivity.ktindex 18cba166ed..aba233e69b 100644--- a/health/src/main/java/com/vayunmathur/health/MainActivity.kt+++ b/health/src/main/java/com/vayunmathur/health/MainActivity.kt@@ -154,6 +154,7 @@ val PERMISSIONS = CLASSES.map { HealthPermission.getReadPermission(it) }.toSet() ) +/** Main Activity: a ma activity implementation for main activity. */ class MainActivity : MaActivity() { private val healthViewModel: HealthViewModel by viewModels { HealthViewModelFactory(application, HealthRepository.get(this))@@ -268,35 +269,46 @@ class MainActivity : MaActivity() { } } +/** Contract for route. */ @Serializable sealed interface Route: NavKey {+ /** Singleton holding today state and operations. */ @Serializable data object Today: Route + /** Singleton holding body state and operations. */ @Serializable data object Body: Route + /** Singleton holding nutrition details state and operations. */ @Serializable data object NutritionDetails: Route + /** Singleton holding nutrition full breakdown state and operations. */ @Serializable data object NutritionFullBreakdown: Route + /** Singleton holding recipe management state and operations. */ @Serializable data object RecipeManagement: Route + /** Immutable value describing recipe editor; carries recipeId. */ @Serializable data class RecipeEditor(val recipeId: String? = null): Route + /** Immutable value describing bar chart details; carries healthMetric. */ @Serializable data class BarChartDetails(val healthMetric: HealthMetricConfig): Route + /** Singleton holding sleep details state and operations. */ @Serializable data object SleepDetails: Route + /** Singleton holding exercise details state and operations. */ @Serializable data object ExerciseDetails: Route + /** Singleton holding medical state and operations. */ @Serializable data object Medical: Route
health/src/main/java/com/vayunmathur/health/data/FoodModels.kt
diff --git a/health/src/main/java/com/vayunmathur/health/data/FoodModels.kt b/health/src/main/java/com/vayunmathur/health/data/FoodModels.ktindex a1e8bb4a60..53c0cedacf 100644--- a/health/src/main/java/com/vayunmathur/health/data/FoodModels.kt+++ b/health/src/main/java/com/vayunmathur/health/data/FoodModels.kt@@ -9,6 +9,7 @@ import androidx.room3.ForeignKey import androidx.room3.Index import androidx.room3.PrimaryKey +/** Immutable value describing ingredient. */ @Entity data class Ingredient( @PrimaryKey val id: String, // Unique identifier, possibly from API@@ -22,6 +23,7 @@ data class Ingredient( get() = customName ?: originalName } +/** Immutable value describing recipe. */ @Entity data class Recipe( @PrimaryKey val id: String = Uuid.random().toString(),@@ -48,6 +50,7 @@ data class Recipe( Index("recipeId") ] )+/** Immutable value describing serving unit. */ data class ServingUnit( @PrimaryKey val id: String = Uuid.random().toString(), val ingredientId: String? = null,@@ -84,6 +87,7 @@ data class ServingUnit( Index("unitId") ] )+/** Immutable value describing recipe ingredient. */ data class RecipeIngredient( @PrimaryKey val id: String = Uuid.random().toString(), val recipeId: String,
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 875131d805..d362acb2a1 100644--- a/health/src/main/java/com/vayunmathur/health/data/HealthRepository.kt+++ b/health/src/main/java/com/vayunmathur/health/data/HealthRepository.kt@@ -193,6 +193,7 @@ class HealthRepository private constructor(context: Context) : */ internal val database: HealthDatabase get() = db + /** Shared constants and helpers for HealthRepository. */ companion object { @Volatile private var instance: HealthRepository? = null
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 d464735f02..b33874db33 100644--- a/health/src/main/java/com/vayunmathur/health/data/MedicalRecords.kt+++ b/health/src/main/java/com/vayunmathur/health/data/MedicalRecords.kt@@ -206,6 +206,7 @@ data class HealthProfile( val smokingFhirId: String? = null, val dataSourceId: String? = null, ) {+ /** Shared constants and helpers for HealthProfile. */ companion object { /** There is only ever one profile, so its key is a constant rather than a generated id. */ const val SINGLETON_ID = "profile"@@ -256,6 +257,7 @@ data class PendingMirror(val kind: MedicalKind, val rowId: String) @Dao // Query surface of the medical tables // Splitting the interface would only move the same method count to more files.+/** Contract for medical dao. */ @Suppress("TooManyFunctions") interface MedicalDao {
health/src/main/java/com/vayunmathur/health/data/MedicationSchedule.kt
diff --git a/health/src/main/java/com/vayunmathur/health/data/MedicationSchedule.kt b/health/src/main/java/com/vayunmathur/health/data/MedicationSchedule.ktindex 80d69af76e..13137dc879 100644--- a/health/src/main/java/com/vayunmathur/health/data/MedicationSchedule.kt+++ b/health/src/main/java/com/vayunmathur/health/data/MedicationSchedule.kt@@ -50,6 +50,7 @@ data class MedicationSchedule( val endDate: LocalDate? = null, ) +/** Contract for schedule dao. */ @Dao interface ScheduleDao {
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 591260343b..c3d55911bc 100644--- a/health/src/main/java/com/vayunmathur/health/data/Record.kt+++ b/health/src/main/java/com/vayunmathur/health/data/Record.kt@@ -19,6 +19,7 @@ import kotlinx.serialization.Serializable import kotlinx.coroutines.flow.Flow import java.time.Instant +/** Kinds of record type. */ enum class RecordType { Steps, Wheelchair, Distance, CaloriesTotal, CaloriesActive, CaloriesBasal, Floors, Elevation, HeartRate, RestingHeartRate, HeartRateVariabilityRmssd, RespiratoryRate, OxygenSaturation,@@ -27,6 +28,7 @@ enum class RecordType { Sleep, Mindfulness, Hydration, Nutrition, Exercise } +/** Immutable value describing nutrition data. */ @Serializable data class NutritionData( val protein: Double = 0.0,@@ -72,6 +74,7 @@ data class NutritionData( val calories: Double = 0.0 ) +/** Immutable value describing sleep stage. */ @Serializable data class SleepStage( val startTimeMillis: Long,@@ -79,6 +82,7 @@ data class SleepStage( val stage: Int ) +/** Immutable value describing sleep data. */ @Serializable data class SleepData( val awakeDurationMillis: Long = 0,@@ -89,6 +93,7 @@ data class SleepData( val stagesJson: String? = null ) +/** Immutable value describing exercise segment data. */ @Serializable data class ExerciseSegmentData( val startTimeMillis: Long,@@ -97,6 +102,7 @@ data class ExerciseSegmentData( val repetitions: Int, ) +/** Immutable value describing exercise lap data. */ @Serializable data class ExerciseLapData( val startTimeMillis: Long,@@ -104,6 +110,7 @@ data class ExerciseLapData( val lengthMeters: Double?, ) +/** Immutable value describing exercise data. */ @Serializable data class ExerciseData( val exerciseType: Int = 0,@@ -114,6 +121,7 @@ data class ExerciseData( val hasRoute: Boolean = false, ) +/** Immutable value describing record. */ @Entity(indices = [Index(value = ["type", "startTime", "endTime"])]) data class Record( val id: String,@@ -133,6 +141,7 @@ data class Record( @Dao // Query surface of the fitness-record tables: one method per query by Room's design. // Splitting the interface would only move the same method count to more files.+/** Contract for health dao. */ @Suppress("TooManyFunctions") interface HealthDao { @Insert(onConflict = OnConflictStrategy.REPLACE)@@ -293,11 +302,13 @@ interface HealthDao { ): List<HourlySum> // Helper data class to catch the results+ /** Immutable value describing daily sum. */ data class DailySum( val day: String, // Format: YYYY-MM-DD val totalValue: Double, val totalValue2: Double )+ /** Immutable value describing hourly sum. */ data class HourlySum( val hourBlock: String, // Format: 2026-03-03 15:00 val totalValue: Double,@@ -374,12 +385,14 @@ interface HealthDao { version = 12, exportSchema = false )+/** Health Database: a room database implementation for health database. */ @ColumnTypeConverters(Converters::class) abstract class HealthDatabase : RoomDatabase() { abstract fun healthDao(): HealthDao abstract fun medicalDao(): MedicalDao abstract fun scheduleDao(): ScheduleDao + /** Shared constants and helpers for HealthDatabase. */ companion object : com.vayunmathur.library.util.DatabaseMigrations { override val migrations = listOf( Migration(4, 5) {@@ -615,6 +628,7 @@ abstract class HealthDatabase : RoomDatabase() { } } +/** Type representing converters. */ class Converters { @ColumnTypeConverter fun fromTimestamp(value: Long?): Instant? = value?.let { Instant.ofEpochMilli(it) }
health/src/main/java/com/vayunmathur/health/data/ReferenceCatalog.kt
diff --git a/health/src/main/java/com/vayunmathur/health/data/ReferenceCatalog.kt b/health/src/main/java/com/vayunmathur/health/data/ReferenceCatalog.ktindex 452f67aa3d..43f4a106d6 100644--- a/health/src/main/java/com/vayunmathur/health/data/ReferenceCatalog.kt+++ b/health/src/main/java/com/vayunmathur/health/data/ReferenceCatalog.kt@@ -93,18 +93,22 @@ object ReferenceCatalog { val icd10Year: Int = 0, ) + /** Contract for status. */ sealed interface Status { val installed: Meta? get() = null /** Not unpacked yet; the pickers accept free text only. */ data object Absent : Status + /** Singleton holding preparing state and operations. */ data object Preparing : Status + /** Immutable value describing ready; carries meta. */ data class Ready(val meta: Meta) : Status { override val installed: Meta get() = meta } + /** Immutable value describing failed; carries message, installed. */ data class Failed(val message: String, override val installed: Meta?) : Status }
health/src/main/java/com/vayunmathur/health/data/VaccineCatalog.kt
diff --git a/health/src/main/java/com/vayunmathur/health/data/VaccineCatalog.kt b/health/src/main/java/com/vayunmathur/health/data/VaccineCatalog.ktindex ef71691019..3db211a677 100644--- a/health/src/main/java/com/vayunmathur/health/data/VaccineCatalog.kt+++ b/health/src/main/java/com/vayunmathur/health/data/VaccineCatalog.kt@@ -23,6 +23,7 @@ object VaccineCatalog { private const val TAG = "VaccineCatalog" private const val ASSET = "cvx.json" + /** Immutable value describing vaccine. */ @Serializable data class Vaccine( /** CVX code, e.g. "208". Kept as a string because FHIR codes are strings. */
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 2069e24eb1..7db383b6e7 100644--- a/health/src/main/java/com/vayunmathur/health/domain/FhirMedication.kt+++ b/health/src/main/java/com/vayunmathur/health/domain/FhirMedication.kt@@ -84,6 +84,23 @@ private fun JsonObjectBuilder.putMedicationConcept(entry: MedicationEntry) { * Times of day become `timeOfDay`, the interval and its unit become `period` and `periodUnit`, * and chosen weekdays become `dayOfWeek`. */++/** Times of day and the derived frequency for a schedule's repeat. */+private fun JsonObjectBuilder.putScheduleTimes(+ schedule: MedicationSchedule,+ weekly: Boolean,+ doseDays: Int,+) {+ if (schedule.times.isEmpty()) return+ putJsonArray("timeOfDay") {+ schedule.times.sorted().forEach { add(JsonPrimitive(formatTimeOfDay(it))) }+ }+ // 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))+ }+} private fun JsonObjectBuilder.putRepeat(entry: MedicationEntry, schedule: MedicationSchedule?) { putJsonObject("repeat") { putJsonObject("boundsPeriod") {@@ -99,16 +116,7 @@ private fun JsonObjectBuilder.putRepeat(entry: MedicationEntry, schedule: Medica 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 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))- }- }+ putScheduleTimes(schedule, weekly, doseDays) put("period", schedule.interval) put("periodUnit", if (weekly) "wk" else "d") if (weekly && doseDays > 0) {@@ -169,15 +177,32 @@ private fun JsonObject.medicationName(): Pair<String, String?>? { * 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. */++/** The shared medication header: root, id, display name and RxCUI. */+private data class MedHeader(+ val root: JsonObject,+ val id: String,+ val displayName: String,+ val rxcui: String?,+)++/** Parses and type-checks the resource header; null when it is not a [type] with a name. */+private fun medHeader(data: String, type: String): MedHeader? {+ val root = parseObject(data) ?: return null+ if (root.string("resourceType") != type) return null+ val id = root.string("id") ?: return null+ val (displayName, rxcui) = root.medicationName() ?: return null+ return MedHeader(root, id, displayName, rxcui)+} internal fun parseMedicationRequest( data: String, dataSourceId: String, ): Pair<MedicationEntry, MedicationSchedule?>? {- val root = parseObject(data) ?: return null- if (root.string("resourceType") != "MedicationRequest") return null- val id = root.string("id") ?: return null+ val header = medHeader(data, "MedicationRequest") ?: return null+ val root = header.root+ val id = header.id val status = requestStatusFromFhir(root.string("status")) ?: return null- val (displayName, rxcui) = root.medicationName() ?: return null+ val (displayName, rxcui) = header.displayName to header.rxcui val dosage = (root["dosageInstruction"] as? JsonArray)?.firstOrNull() as? JsonObject val repeat = ((dosage?.get("timing") as? JsonObject)?.get("repeat")) as? JsonObject@@ -211,12 +236,12 @@ internal fun parseMedicationRequest( * 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+ val header = medHeader(data, "MedicationStatement") ?: return null+ val root = header.root if (root.basedOnRequestId() != null) return null- val id = root.string("id") ?: return null+ val id = header.id val status = statementStatusFromFhir(root.string("status")) ?: return null- val (displayName, rxcui) = root.medicationName() ?: return null+ val (displayName, rxcui) = header.displayName to header.rxcui val period = root["effectivePeriod"] as? JsonObject val startedAt = parseDateTime(root.string("effectiveDateTime"))@@ -250,6 +275,31 @@ internal fun isUnplannedMedicationStatement(data: String): Boolean { return root.string("resourceType") == "MedicationStatement" && root.basedOnRequestId() == null } ++/** The repeat unit and interval, normalising daily-on-weekdays to weekly. */+private fun repeatUnitInterval(+ periodUnit: String?,+ days: Int,+ intervalIn: Int,+): Pair<RepeatUnit, Int>? {+ var unit = when (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+ }+ var interval = intervalIn+ 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 unit to interval+} private fun parseRepeat( repeat: JsonObject, medicationId: String,@@ -266,29 +316,16 @@ private fun parseRepeat( // 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()+ val parsedInterval = 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+ val (unit, interval) = repeatUnitInterval(repeat.string("periodUnit"), days, parsedInterval)+ ?: return null return MedicationSchedule( id = medicationId,@@ -352,8 +389,9 @@ internal fun doseEventJson(event: DoseEvent, medication: MedicationEntry): Strin */ 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+ if (root.string("resourceType") != "MedicationStatement" || root.string("status") != "completed") {+ return null+ } val id = root.string("id") ?: return null val takenAt = parseDateTime(root.string("effectiveDateTime")) ?: return null val requestId = root.basedOnRequestId() ?: return null
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 0dc0efa2ea..d75b7e1fe0 100644--- a/health/src/main/java/com/vayunmathur/health/domain/FhirRecords.kt+++ b/health/src/main/java/com/vayunmathur/health/domain/FhirRecords.kt@@ -145,21 +145,12 @@ object FhirRecords { recordedAt: Instant, ): String = com.vayunmathur.health.domain.socialHistoryAnswerJson(id, question, answer, recordedAt) - fun parseSocialHistoryAnswer(data: String): String? =- com.vayunmathur.health.domain.parseSocialHistoryAnswer(data) fun parseLabResult(data: String, dataSourceId: String): LabResultEntry? = com.vayunmathur.health.domain.parseLabResult(data, dataSourceId) - fun observationLoincCode(data: String): String? =- com.vayunmathur.health.domain.observationLoincCode(data) - /** The resource's own `id`, needed to update rather than duplicate it on the next write. */- fun resourceId(data: String): String? =- com.vayunmathur.health.domain.resourceId(data) - fun observationEffective(data: String): Instant? =- com.vayunmathur.health.domain.observationEffective(data) fun parsePregnancyStatus(data: String): Pair<PregnancyStatus, Instant?>? = com.vayunmathur.health.domain.parsePregnancyStatus(data)@@ -181,3 +172,20 @@ object FhirRecords { internal fun parseQuantity(text: String): Pair<Double, String>? = com.vayunmathur.health.domain.parseQuantity(text) }++/** Observation-level FHIR helpers, split out of [FhirRecords]. */+object FhirObservations {+ fun parseSocialHistoryAnswer(data: String): String? =+ com.vayunmathur.health.domain.parseSocialHistoryAnswer(data)++ fun observationLoincCode(data: String): String? =+ com.vayunmathur.health.domain.observationLoincCode(data)++ /** The resource's own `id`, needed to update rather than duplicate it on the next write. */++ fun resourceId(data: String): String? =+ com.vayunmathur.health.domain.resourceId(data)++ fun observationEffective(data: String): Instant? =+ com.vayunmathur.health.domain.observationEffective(data)+}
health/src/main/java/com/vayunmathur/health/domain/SocialHistoryQuestions.kt
diff --git a/health/src/main/java/com/vayunmathur/health/domain/SocialHistoryQuestions.kt b/health/src/main/java/com/vayunmathur/health/domain/SocialHistoryQuestions.ktindex fee4c6f55b..fee5ae5eb0 100644--- a/health/src/main/java/com/vayunmathur/health/domain/SocialHistoryQuestions.kt+++ b/health/src/main/java/com/vayunmathur/health/domain/SocialHistoryQuestions.kt@@ -30,6 +30,7 @@ object SocialHistoryQuestions { */ data class Answer(val code: String, val display: String, val labelRes: Int) + /** Immutable value describing question. */ data class Question( /** LOINC code for the question itself, used as `Observation.code`. */ val loinc: 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 6d41f18f0e..9452d75450 100644--- a/health/src/main/java/com/vayunmathur/health/platform/DoseActionReceiver.kt+++ b/health/src/main/java/com/vayunmathur/health/platform/DoseActionReceiver.kt@@ -77,6 +77,7 @@ class DoseActionReceiver : BroadcastReceiver() { } } + /** Shared constants and helpers for DoseActionReceiver. */ companion object { const val ACTION_TAKEN = "com.vayunmathur.health.DOSE_TAKEN" const val ACTION_SNOOZE = "com.vayunmathur.health.DOSE_SNOOZE"
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 61e1eb6ab7..c2aaccba6b 100644--- a/health/src/main/java/com/vayunmathur/health/platform/MedicalImportOps.kt+++ b/health/src/main/java/com/vayunmathur/health/platform/MedicalImportOps.kt@@ -8,6 +8,7 @@ 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.FhirObservations import com.vayunmathur.health.domain.FhirRecords import com.vayunmathur.health.domain.SocialHistoryQuestions import kotlinx.coroutines.launch@@ -97,24 +98,40 @@ private suspend fun <Row : Any, Parsed : Any> MedicalViewModel.reconcile( 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+ reconcileOne(kind, resource, own, find, getById, rowIdOf, parse, retract, store)+ }+} - 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)+/** Applies one resource within [reconcile]; see its contract. */+@Suppress("LongParameterList")+private suspend fun <Row : Any, Parsed : Any> MedicalViewModel.reconcileOne(+ kind: MedicalKind,+ resource: 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,+) {+ val source = resource.dataSourceId+ val fhirId = FhirObservations.resourceId(resource.data) ?: return+ if (repository.isTombstoned(kind, source, fhirId)) return+ val isOwn = source == own || PersonalHealthRecords.isOwnDataSource(source)+ val existing = find(source, fhirId)+ if (existing != null && isOwn) return++ if (FhirRecords.isEnteredInError(resource.data)) {+ existing?.let { retract(it) }+ return }+ val incoming = parse(resource) ?: return+ 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+ store(incoming, rowId, existing) } private suspend fun MedicalViewModel.importVaccinesAndMeds(own: String?) {@@ -219,7 +236,7 @@ private suspend fun MedicalViewModel.migrateLegacyStatements( legacy: List<PersonalHealthRecords.RawResource>, ) { legacy.forEach { resource ->- val fhirId = FhirRecords.resourceId(resource.data) ?: return@forEach+ val fhirId = FhirObservations.resourceId(resource.data) ?: return@forEach val local = repository.findMedication(resource.dataSourceId, fhirId) val rowId = when { local != null -> local.id@@ -303,7 +320,7 @@ private suspend fun MedicalViewModel.importProfile() { val newest = mutableMapOf<String, ProfileAnswer>() resources.forEach { resource ->- val loinc = FhirRecords.observationLoincCode(resource.data)+ val loinc = FhirObservations.observationLoincCode(resource.data) when (loinc) { FhirRecords.LOINC_PREGNANCY_STATUS -> applyPregnancy(resource, profile).also { profile = it } FhirRecords.LOINC_SMOKING_STATUS -> applySmoking(resource, profile).also { profile = it }@@ -331,7 +348,7 @@ private fun MedicalViewModel.applyPregnancy( pregnancyStatus = status, dueDate = due, pregnancyFhirId = profile.pregnancyFhirId- ?: FhirRecords.resourceId(resource.data),+ ?: FhirObservations.resourceId(resource.data), ) } ?: profile @@ -343,7 +360,7 @@ private fun MedicalViewModel.applySmoking( profile.copy( smokingStatus = status, smokingFhirId = profile.smokingFhirId- ?: FhirRecords.resourceId(resource.data),+ ?: FhirObservations.resourceId(resource.data), ) } ?: profile @@ -355,7 +372,7 @@ private fun MedicalViewModel.applySocialHistoryAnswer( // Anything else in this category that is one of ours, matched by question code. // A provider's social history contains plenty this app does not ask about. val question = loinc?.let { SocialHistoryQuestions.byLoinc(it) } ?: return- val answerCode = FhirRecords.parseSocialHistoryAnswer(resource.data) ?: return+ val answerCode = FhirObservations.parseSocialHistoryAnswer(resource.data) ?: return // Refuse an answer outside the question's own list rather than storing a code // the selector could never show. if (question.answers.none { it.code == answerCode }) return@@ -365,8 +382,8 @@ private fun MedicalViewModel.applySocialHistoryAnswer( answerCode = answerCode, // The observation's own date, not now. Using now would make every import // look like the freshest answer and would misdate the "Recorded" line.- recordedAt = FhirRecords.observationEffective(resource.data) ?: return,- fhirResourceId = FhirRecords.resourceId(resource.data),+ recordedAt = FhirObservations.observationEffective(resource.data) ?: return,+ fhirResourceId = FhirObservations.resourceId(resource.data), dataSourceId = resource.dataSourceId, ) val held = newest[question.loinc]
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.ktindex a2122519e0..b6e4429a8d 100644--- a/health/src/main/java/com/vayunmathur/health/platform/MedicalMirror.kt+++ b/health/src/main/java/com/vayunmathur/health/platform/MedicalMirror.kt@@ -113,6 +113,14 @@ internal suspend fun HealthRepository.mirrorMedication(id: String): Boolean { } /** Writes a dose as a `MedicationStatement`, mirroring its medication first if that never landed. */++/** The dose's medication, mirrored first when it never landed in Health Connect. */+internal suspend fun HealthRepository.mirroredMedication(event: DoseEvent): MedicationEntry? {+ val unmirrored = getMedication(event.medicationId) ?: return null+ if (unmirrored.fhirResourceId == null && !mirrorMedication(unmirrored.id)) return null+ return getMedication(event.medicationId)+}+ internal suspend fun HealthRepository.mirrorDose(id: String): Boolean { val event = getDoseEvent(id) ?: run { clearPending(MedicalKind.Dose, id)@@ -120,9 +128,7 @@ internal suspend fun HealthRepository.mirrorDose(id: String): Boolean { } 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 medication = mirroredMedication(event) ?: return false val written = PersonalHealthRecords.upsert( target,
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 506c423a98..9650b6d97f 100644--- a/health/src/main/java/com/vayunmathur/health/platform/MedicalViewModel.kt+++ b/health/src/main/java/com/vayunmathur/health/platform/MedicalViewModel.kt@@ -76,6 +76,7 @@ class MedicalViewModel( internal val repository: HealthRepository = HealthRepository.get(application), ) : AndroidViewModel(application) { + /** Shared constants and helpers for MedicalViewModel. */ companion object { /** 9am in seconds since midnight: the default time of a new reminder schedule. */ internal const val DEFAULT_DOSE_TIME_SECONDS = 9 * 60 * 60@@ -177,6 +178,7 @@ class MedicalViewModel( get() = savedAttachments.filterNot { it.id in removedAttachmentIds } } + /** Immutable value describing medication draft. */ data class MedicationDraft( val editingId: String? = null, val rxcui: String? = null,@@ -213,6 +215,7 @@ class MedicalViewModel( internal val medicationDraftState = MutableStateFlow(MedicationDraft()) val medicationDraft: StateFlow<MedicationDraft> = medicationDraftState.asStateFlow() + /** Immutable value describing allergy draft. */ data class AllergyDraft( val editingId: String? = null, val rxcui: String? = null,@@ -224,6 +227,7 @@ class MedicalViewModel( val note: String = "", ) + /** Immutable value describing condition draft. */ data class ConditionDraft( val editingId: String? = null, val icd10Code: String? = null,@@ -234,6 +238,7 @@ class MedicalViewModel( val note: String = "", ) + /** Immutable value describing lab result draft. */ data class LabResultDraft( val editingId: String? = null, val loincCode: String? = null,@@ -395,6 +400,7 @@ class MedicalViewModel( internal fun formatNumber(value: Double): String = if (value == value.toLong().toDouble()) value.toLong().toString() else value.toString() +/** Creates medical view model instances. */ class MedicalViewModelFactory( private val application: Application, private val repository: HealthRepository,
health/src/main/java/com/vayunmathur/health/service/DoseSoundService.kt
diff --git a/health/src/main/java/com/vayunmathur/health/service/DoseSoundService.kt b/health/src/main/java/com/vayunmathur/health/service/DoseSoundService.ktindex 82e596f67c..34cd25a61d 100644--- a/health/src/main/java/com/vayunmathur/health/service/DoseSoundService.kt+++ b/health/src/main/java/com/vayunmathur/health/service/DoseSoundService.kt@@ -160,6 +160,7 @@ class DoseSoundService : Service() { override fun onBind(intent: Intent?) = null + /** Shared constants and helpers for DoseSoundService. */ companion object { const val EXTRA_MEDICATION_NAME = "MEDICATION_NAME" private const val TAG = "DoseSoundService"
health/src/main/java/com/vayunmathur/health/ui/FoodLoggingDialogs.kt
diff --git a/health/src/main/java/com/vayunmathur/health/ui/FoodLoggingDialogs.kt b/health/src/main/java/com/vayunmathur/health/ui/FoodLoggingDialogs.ktindex a400e97296..2a2c063018 100644--- a/health/src/main/java/com/vayunmathur/health/ui/FoodLoggingDialogs.kt+++ b/health/src/main/java/com/vayunmathur/health/ui/FoodLoggingDialogs.kt@@ -39,6 +39,7 @@ import com.vayunmathur.health.data.Recipe import com.vayunmathur.health.util.HealthViewModel import java.time.Instant +/** Kinds of hydration unit. */ enum class HydrationUnit(@StringRes val displayName: Int, val toLiters: Double) { Liters(R.string.hydration_liters, 1.0), Milliliters(R.string.hydration_milliliters, 0.001),@@ -114,15 +115,18 @@ fun LogHydrationDialog(viewModel: HealthViewModel, initialTime: Instant? = null, ) } +/** Type representing loggable. */ sealed class Loggable { abstract val id: String abstract val name: String + /** Immutable value describing recipe wrapper; carries recipe. */ data class RecipeWrapper(val recipe: Recipe) : Loggable() { override val id = recipe.id override val name = recipe.name } + /** Immutable value describing ingredient wrapper; carries ingredient. */ data class IngredientWrapper(val ingredient: Ingredient) : Loggable() { override val id = ingredient.id override val name = ingredient.displayName
health/src/main/java/com/vayunmathur/health/ui/MetricDashboardData.kt
diff --git a/health/src/main/java/com/vayunmathur/health/ui/MetricDashboardData.kt b/health/src/main/java/com/vayunmathur/health/ui/MetricDashboardData.ktindex 2700cf45b7..5feac907d8 100644--- a/health/src/main/java/com/vayunmathur/health/ui/MetricDashboardData.kt+++ b/health/src/main/java/com/vayunmathur/health/ui/MetricDashboardData.kt@@ -1,5 +1,6 @@ package com.vayunmathur.health.ui +/** Immutable value describing metric dashboard data. */ data class MetricDashboardData( val totalValue: Double = 0.0, val dailyAverage: Double = 0.0,@@ -11,6 +12,7 @@ data class MetricDashboardData( val totalBarCount: Int = 0 ) +/** Immutable value describing history item. */ data class HistoryItem( val label: String, val value: Double,
health/src/main/java/com/vayunmathur/health/ui/NutritionPage.kt
diff --git a/health/src/main/java/com/vayunmathur/health/ui/NutritionPage.kt b/health/src/main/java/com/vayunmathur/health/ui/NutritionPage.ktindex e86d1a4ae3..71abb2d0ba 100644--- a/health/src/main/java/com/vayunmathur/health/ui/NutritionPage.kt+++ b/health/src/main/java/com/vayunmathur/health/ui/NutritionPage.kt@@ -58,6 +58,7 @@ import com.vayunmathur.library.util.round import kotlin.time.Clock import kotlin.time.Duration.Companion.hours +/** Immutable value describing nutrient dv. */ data class NutrientDV( val name: String, val dailyValue: Double,
health/src/main/java/com/vayunmathur/health/ui/PermissionsRationaleActivity.kt
diff --git a/health/src/main/java/com/vayunmathur/health/ui/PermissionsRationaleActivity.kt b/health/src/main/java/com/vayunmathur/health/ui/PermissionsRationaleActivity.ktindex ab7d617cf9..4f627be3b6 100644--- a/health/src/main/java/com/vayunmathur/health/ui/PermissionsRationaleActivity.kt+++ b/health/src/main/java/com/vayunmathur/health/ui/PermissionsRationaleActivity.kt@@ -1,4 +1,5 @@ package com.vayunmathur.health.ui import android.app.Activity +/** Permissions Rationale Activity: a activity implementation for permissions rationale activity. */ class PermissionsRationaleActivity: Activity()
health/src/main/java/com/vayunmathur/health/ui/RecipeEditorPage.kt
diff --git a/health/src/main/java/com/vayunmathur/health/ui/RecipeEditorPage.kt b/health/src/main/java/com/vayunmathur/health/ui/RecipeEditorPage.ktindex a09abd51d3..31ac7d795b 100644--- a/health/src/main/java/com/vayunmathur/health/ui/RecipeEditorPage.kt+++ b/health/src/main/java/com/vayunmathur/health/ui/RecipeEditorPage.kt@@ -177,6 +177,7 @@ fun RecipeEditorPage(backStack: NavBackStack<Route>, viewModel: HealthViewModel, } } +/** Immutable value describing recipe ingredient data. */ data class RecipeIngredientData( val ingredient: Ingredient, val unit: ServingUnit,
health/src/main/java/com/vayunmathur/health/util/FoodDatabase.kt
diff --git a/health/src/main/java/com/vayunmathur/health/util/FoodDatabase.kt b/health/src/main/java/com/vayunmathur/health/util/FoodDatabase.ktindex 13ec3ece39..f45601c05e 100644--- a/health/src/main/java/com/vayunmathur/health/util/FoodDatabase.kt+++ b/health/src/main/java/com/vayunmathur/health/util/FoodDatabase.kt@@ -133,6 +133,7 @@ object FoodDatabase { val compressedBytes: Long = 0, ) + /** Contract for status. */ sealed interface Status { /** The database that is unpacked and searchable right now, if any. */ val installed: Meta? get() = null@@ -143,10 +144,12 @@ object FoodDatabase { /** First-run construction of the database, in products written. */ data class Preparing(val productsWritten: Long, val totalProducts: Long) : Status + /** Immutable value describing ready; carries meta. */ data class Ready(val meta: Meta) : Status { override val installed: Meta get() = meta } + /** Immutable value describing failed; carries message, installed. */ data class Failed(val message: String, override val installed: Meta?) : Status }
health/src/main/java/com/vayunmathur/health/util/FoodSearchAPI.kt
diff --git a/health/src/main/java/com/vayunmathur/health/util/FoodSearchAPI.kt b/health/src/main/java/com/vayunmathur/health/util/FoodSearchAPI.ktindex 1119938be7..ad2b214327 100644--- a/health/src/main/java/com/vayunmathur/health/util/FoodSearchAPI.kt+++ b/health/src/main/java/com/vayunmathur/health/util/FoodSearchAPI.kt@@ -17,6 +17,7 @@ import com.vayunmathur.health.data.Ingredient */ object FoodSearchAPI { + /** Immutable value describing search result; carries id, displayName. */ data class SearchResult(val id: Long, val displayName: String) /** Ranked name matches from the downloaded bundle; empty if it isn't installed. */
health/src/main/java/com/vayunmathur/health/util/HealthAPI.kt
diff --git a/health/src/main/java/com/vayunmathur/health/util/HealthAPI.kt b/health/src/main/java/com/vayunmathur/health/util/HealthAPI.ktindex 32fd3186f5..1f254e5f34 100644--- a/health/src/main/java/com/vayunmathur/health/util/HealthAPI.kt+++ b/health/src/main/java/com/vayunmathur/health/util/HealthAPI.kt@@ -33,6 +33,7 @@ import kotlinx.datetime.LocalDateTime import kotlinx.datetime.minus import kotlinx.datetime.plus +/** Singleton holding health api state and operations. */ object HealthAPI { private var healthConnectClient: HealthConnectClient? = null lateinit var preferences: SharedPreferences@@ -255,6 +256,7 @@ object HealthAPI { metadata = Metadata.manualEntry(clientRecordId = record.id), ) + /** Kinds of period type. */ enum class PeriodType { Hourly, Daily,
health/src/main/java/com/vayunmathur/health/util/HealthChartData.kt
diff --git a/health/src/main/java/com/vayunmathur/health/util/HealthChartData.kt b/health/src/main/java/com/vayunmathur/health/util/HealthChartData.ktindex 64034715f3..5b87f6d904 100644--- a/health/src/main/java/com/vayunmathur/health/util/HealthChartData.kt+++ b/health/src/main/java/com/vayunmathur/health/util/HealthChartData.kt@@ -31,6 +31,8 @@ import kotlinx.datetime.toLocalDateTime * framework access except formatted strings, which callers pass in. */ internal object HealthChartData {+ private const val METERS_TO_CM = 100.0+ /** Sunday..Saturday slot count for the week tab. */ internal const val DAYS_PER_WEEK = 7@@ -112,7 +114,7 @@ internal object HealthChartData { pairs: List<Tuple3<Long, Double, Double>>, ): List<Tuple3<Long, Double, Double>> { if (config.recordType != com.vayunmathur.health.data.RecordType.Height) return pairs- return pairs.map { Tuple3(it.first, it.second * 100.0, it.third * 100.0) }+ return pairs.map { Tuple3(it.first, it.second * METERS_TO_CM, it.third * METERS_TO_CM) } } /**@@ -163,8 +165,6 @@ internal object HealthChartData { config: HealthMetricConfig, selectedTab: Int, startDate: LocalDate,- startTime: kotlin.time.Instant,- tz: TimeZone, resources: Resources, rawPairsHistory: List<Tuple3<Long, Double, Double>>, ): List<HistoryItem> {
health/src/main/java/com/vayunmathur/health/util/HealthSyncWorker.kt
diff --git a/health/src/main/java/com/vayunmathur/health/util/HealthSyncWorker.kt b/health/src/main/java/com/vayunmathur/health/util/HealthSyncWorker.ktindex 2e2f1434eb..69d1b4a085 100644--- a/health/src/main/java/com/vayunmathur/health/util/HealthSyncWorker.kt+++ b/health/src/main/java/com/vayunmathur/health/util/HealthSyncWorker.kt@@ -142,6 +142,7 @@ class HealthSyncWorker( } while (response.hasMore) } + /** Shared constants and helpers for HealthSyncWorker. */ companion object { private const val TAG = "HealthSyncWorker"
health/src/main/java/com/vayunmathur/health/util/HealthUiContract.kt
diff --git a/health/src/main/java/com/vayunmathur/health/util/HealthUiContract.kt b/health/src/main/java/com/vayunmathur/health/util/HealthUiContract.ktindex 517bec603d..6f13b4a50a 100644--- a/health/src/main/java/com/vayunmathur/health/util/HealthUiContract.kt+++ b/health/src/main/java/com/vayunmathur/health/util/HealthUiContract.kt@@ -48,6 +48,7 @@ interface TodayActions { fun openExerciseDetails() {} fun openMetric(config: HealthMetricConfig) {} + /** Shared constants and helpers for TodayActions. */ companion object { val Noop: TodayActions = object : TodayActions {} }@@ -70,6 +71,7 @@ interface NutritionActions { fun openRecipes() {} fun openFullBreakdown() {} + /** Shared constants and helpers for NutritionActions. */ companion object { val Noop: NutritionActions = object : NutritionActions {} }@@ -89,6 +91,7 @@ interface MetricDetailsActions { fun loadBarChartData(config: HealthMetricConfig, anchorDate: LocalDate, selectedTab: Int) {} fun navigateUp() {} + /** Shared constants and helpers for MetricDetailsActions. */ companion object { val Noop: MetricDetailsActions = object : MetricDetailsActions {} }
health/src/main/java/com/vayunmathur/health/util/HealthViewModel.kt
diff --git a/health/src/main/java/com/vayunmathur/health/util/HealthViewModel.kt b/health/src/main/java/com/vayunmathur/health/util/HealthViewModel.ktindex 9472cce15d..87cd6b036f 100644--- a/health/src/main/java/com/vayunmathur/health/util/HealthViewModel.kt+++ b/health/src/main/java/com/vayunmathur/health/util/HealthViewModel.kt@@ -253,7 +253,7 @@ class HealthViewModel( config, selectedTab, startDate, rawPairs, is24Hour(getApplication()), ) val history = HealthChartData.buildHistoryItems(- config, selectedTab, startDate, startTime, tz, resources, rawPairsHistory,+ config, selectedTab, startDate, resources, rawPairsHistory, ) _barChartData.value = HealthChartData.buildDashboardData(@@ -303,8 +303,11 @@ class HealthViewModel( } } + /** Type representing log meal target. */ sealed class LogMealTarget {+ /** Immutable value describing from recipe; carries recipeId, name. */ data class FromRecipe(val recipeId: String, val name: String) : LogMealTarget()+ /** Immutable value describing from ingredient; carries ingredient. */ data class FromIngredient(val ingredient: Ingredient) : LogMealTarget() } @@ -464,6 +467,7 @@ class HealthViewModel( foodDatabaseJob = viewModelScope.launch { FoodDatabase.prepare() } } + /** Shared constants and helpers for HealthViewModel. */ companion object { private const val TAG = "HealthViewModel" @@ -490,6 +494,7 @@ class HealthViewModel( } } +/** Creates health view model instances. */ class HealthViewModelFactory( private val application: Application, private val repository: HealthRepository,
health/src/test/java/com/vayunmathur/health/domain/FhirRecordsParsingTest.kt
diff --git a/health/src/test/java/com/vayunmathur/health/domain/FhirRecordsParsingTest.kt b/health/src/test/java/com/vayunmathur/health/domain/FhirRecordsParsingTest.ktnew file mode 100644index 0000000000..e12eb96746--- /dev/null+++ b/health/src/test/java/com/vayunmathur/health/domain/FhirRecordsParsingTest.kt@@ -0,0 +1,548 @@+package com.vayunmathur.health.domain++import com.vayunmathur.health.data.AllergyCategory+import com.vayunmathur.health.data.AllergyCriticality+import com.vayunmathur.health.data.AllergyEntry+import com.vayunmathur.health.data.ConditionEntry+import com.vayunmathur.health.data.ConditionStatus+import com.vayunmathur.health.data.DoseEvent+import com.vayunmathur.health.data.LabResultEntry+import com.vayunmathur.health.data.MedicationSchedule+import com.vayunmathur.health.data.PregnancyStatus+import com.vayunmathur.health.data.RepeatUnit+import com.vayunmathur.health.data.SmokingStatus+import kotlinx.datetime.LocalDate as KotlinLocalDate+import com.vayunmathur.health.data.MedicationEntry+import com.vayunmathur.health.data.MedicationStatus+import com.vayunmathur.health.data.VaccinationEntry+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.JsonObject+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++/**+ * Health Connect validates FHIR resources on write, so the shape of what [FhirRecords] emits is not+ * cosmetic: a missing required field is a rejected record. These cover the required fields, the+ * round trip, and the reading of resources looser than anything this app writes.+ */+class FhirRecordsParsingTest {++ 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++ private val flu = VaccinationEntry(+ id = "vac-1",+ cvxCode = "158",+ displayName = "influenza, injectable, quadrivalent",+ occurredAt = Instant.parse("2026-03-04T09:30:00Z"),+ lotNumber = "AB1234",+ site = "Left arm",+ route = "Intramuscular",+ doseQuantity = "0.5 mL",+ performer = "Boots Pharmacy",+ note = "Annual",+ )++ private val amoxicillin = MedicationEntry(+ id = "med-1",+ rxcui = "308182",+ displayName = "amoxicillin",+ strength = "250 MG",+ doseForm = "Oral Capsule",+ status = MedicationStatus.Completed,+ startedAt = Instant.parse("2026-01-10T00:00:00Z"),+ endedAt = Instant.parse("2026-01-17T00:00:00Z"),+ dosageText = "One capsule three times a day",+ )++ // --- Immunization --------------------------------------------------------++ @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+ fun `a provider resource with a date-only occurrence and no CVX still parses`() {+ val provider = """+ {+ "resourceType": "Immunization",+ "id": "provider-1",+ "status": "completed",+ "vaccineCode": {+ "coding": [+ { "system": "http://snomed.info/sct", "code": "1119349007", "display": "COVID-19 vaccine" }+ ]+ },+ "patient": { "reference": "Patient/other" },+ "occurrenceDateTime": "2021-04-19"+ }+ """.trimIndent()++ val parsed = FhirRecords.parseImmunization(provider, "hospital")++ assertNotNull(parsed)+ assertNull(parsed.cvxCode)+ assertEquals("COVID-19 vaccine", parsed.displayName)+ assertEquals(Instant.parse("2021-04-19T00:00:00Z"), parsed.occurredAt)+ }++ @Test+ fun `unknown statuses are treated as still being taken`() {+ val provider = """+ {+ "resourceType": "MedicationRequest",+ "id": "provider-2",+ "status": "unknown",+ "intent": "order",+ "medicationCodeableConcept": { "text": "Metformin" },+ "subject": { "reference": "Patient/other" },+ "authoredOn": "2024-06"+ }+ """.trimIndent()++ val parsed = FhirRecords.parseMedicationRequest(provider, "hospital")?.first++ assertNotNull(parsed)+ assertEquals(MedicationStatus.Active, parsed.status)+ assertEquals("Metformin", parsed.displayName)+ assertEquals(Instant.parse("2024-06-01T00:00:00Z"), parsed.startedAt)+ }++ @Test+ fun `the wrong resource type and malformed json are refused, not thrown on`() {+ assertNull(FhirRecords.parseImmunization("{ not json", "src"))+ assertNull(FhirRecords.parseImmunization(FhirRecords.patientJson(), "src"))+ assertNull(FhirRecords.parseMedicationRequest(FhirRecords.immunizationJson(flu), "src"))+ }++ @Test+ fun `the patient resource is minimal and well formed`() {+ val root = parse(FhirRecords.patientJson())++ assertEquals("Patient", root.str("resourceType"))+ assertEquals(FhirRecords.PATIENT_RESOURCE_ID, root.str("id"))+ }++ // --- AllergyIntolerance --------------------------------------------------++ private val penicillin = AllergyEntry(+ id = "alg-1",+ rxcui = "7980",+ displayName = "penicillin G",+ category = AllergyCategory.Medication,+ criticality = AllergyCriticality.High,+ reaction = "anaphylaxis",+ onsetAt = Instant.parse("2019-06-01T00:00:00Z"),+ recordedAt = Instant.parse("2026-03-04T09:30:00Z"),+ )++ @Test+ fun `allergy carries the fields FHIR requires`() {+ val root = parse(FhirRecords.allergyIntoleranceJson(penicillin))++ assertEquals("AllergyIntolerance", root.str("resourceType"))+ assertEquals(+ "Patient/${FhirRecords.PATIENT_RESOURCE_ID}",+ root["patient"]!!.jsonObject.str("reference"),+ )+ assertEquals(+ "active",+ root["clinicalStatus"]!!.jsonObject["coding"]!!.jsonArray.single().jsonObject.str("code"),+ )+ assertEquals("high", root.str("criticality"))+ assertEquals("medication", (root["category"] as JsonArray).single().jsonPrimitive.content)++ val coding = root["code"]!!.jsonObject["coding"]!!.jsonArray.single().jsonObject+ assertEquals(FhirRecords.RXNORM_SYSTEM, coding.str("system"))+ assertEquals("7980", coding.str("code"))+ }++ @Test+ fun `a food allergen has no coding but still has text`() {+ val peanut = penicillin.copy(+ rxcui = null,+ displayName = "peanut",+ category = AllergyCategory.Food,+ )+ val code = parse(FhirRecords.allergyIntoleranceJson(peanut))["code"]!!.jsonObject++ assertNull(code["coding"])+ assertEquals("peanut", code.str("text"))+ }++ @Test+ fun `an unknown criticality is omitted rather than guessed`() {+ val unknown = penicillin.copy(criticality = AllergyCriticality.Unknown)+ assertNull(parse(FhirRecords.allergyIntoleranceJson(unknown))["criticality"])+ }++ @Test+ fun `an allergy round trips`() {+ val parsed = FhirRecords.parseAllergyIntolerance(+ FhirRecords.allergyIntoleranceJson(penicillin),+ "src-1",+ )++ assertNotNull(parsed)+ assertEquals(penicillin.rxcui, parsed.rxcui)+ assertEquals(penicillin.displayName, parsed.displayName)+ assertEquals(penicillin.category, parsed.category)+ assertEquals(penicillin.criticality, parsed.criticality)+ assertEquals(penicillin.reaction, parsed.reaction)+ assertEquals(penicillin.onsetAt, parsed.onsetAt)+ assertEquals(penicillin.recordedAt, parsed.recordedAt)+ }++ // --- Condition -----------------------------------------------------------++ private val diabetes = ConditionEntry(+ id = "cond-1",+ icd10Code = "E11.9",+ displayName = "Type 2 diabetes mellitus without complications",+ status = ConditionStatus.Active,+ onsetAt = Instant.parse("2022-01-15T00:00:00Z"),+ )++ @Test+ fun `condition carries the fields US Core requires`() {+ val root = parse(FhirRecords.conditionJson(diabetes))++ assertEquals("Condition", root.str("resourceType"))+ assertEquals(+ "Patient/${FhirRecords.PATIENT_RESOURCE_ID}",+ root["subject"]!!.jsonObject.str("reference"),+ )+ assertEquals(+ "active",+ root["clinicalStatus"]!!.jsonObject["coding"]!!.jsonArray.single().jsonObject.str("code"),+ )+ // US Core requires a category, and a user-maintained list is a problem list.+ val category = (root["category"] as JsonArray).single().jsonObject+ assertEquals(+ "problem-list-item",+ category["coding"]!!.jsonArray.single().jsonObject.str("code"),+ )+ assertEquals("2022-01-15", root.str("onsetDateTime"))++ val coding = root["code"]!!.jsonObject["coding"]!!.jsonArray.single().jsonObject+ assertEquals(FhirRecords.ICD10_SYSTEM, coding.str("system"))+ assertEquals("E11.9", coding.str("code"))+ }++ @Test+ fun `a resolved condition carries an abatement date`() {+ val resolved = diabetes.copy(+ status = ConditionStatus.Resolved,+ resolvedAt = Instant.parse("2024-08-01T00:00:00Z"),+ )+ val root = parse(FhirRecords.conditionJson(resolved))++ assertEquals(+ "resolved",+ root["clinicalStatus"]!!.jsonObject["coding"]!!.jsonArray.single().jsonObject.str("code"),+ )+ assertEquals("2024-08-01", root.str("abatementDateTime"))+ }++ @Test+ fun `a condition round trips`() {+ val parsed = FhirRecords.parseCondition(FhirRecords.conditionJson(diabetes), "src-1")++ assertNotNull(parsed)+ assertEquals(diabetes.icd10Code, parsed.icd10Code)+ assertEquals(diabetes.displayName, parsed.displayName)+ assertEquals(diabetes.status, parsed.status)+ assertEquals(diabetes.onsetAt, parsed.onsetAt)+ }++ @Test+ fun `a provider condition dated only by period still parses`() {+ val provider = """+ {+ "resourceType": "Condition",+ "id": "provider-3",+ "clinicalStatus": { "coding": [ { "code": "inactive" } ] },+ "code": { "text": "Asthma" },+ "subject": { "reference": "Patient/other" },+ "onsetPeriod": { "start": "2015-04-01" }+ }+ """.trimIndent()++ val parsed = FhirRecords.parseCondition(provider, "hospital")++ assertNotNull(parsed)+ assertEquals("Asthma", parsed.displayName)+ assertEquals(ConditionStatus.Resolved, parsed.status)+ assertEquals(Instant.parse("2015-04-01T00:00:00Z"), parsed.onsetAt)+ }++ @Test+ fun `the allergy and condition parsers refuse each other's resources`() {+ val allergy = FhirRecords.allergyIntoleranceJson(penicillin)+ val condition = FhirRecords.conditionJson(diabetes)++ assertNull(FhirRecords.parseCondition(allergy, "src"))+ assertNull(FhirRecords.parseAllergyIntolerance(condition, "src"))+ }++ // --- Observations --------------------------------------------------------++ private val hba1c = LabResultEntry(+ id = "lab-1",+ loincCode = "4548-4",+ displayName = "Hemoglobin A1c/Hemoglobin.total in Blood",+ value = 5.4,+ unit = "%",+ referenceLow = 4.0,+ referenceHigh = 5.6,+ takenAt = Instant.parse("2026-02-11T08:15:00Z"),+ )++ @Test+ fun `a numeric lab result carries a quantity and its reference range`() {+ val root = parse(FhirRecords.labResultJson(hba1c))++ assertEquals("Observation", root.str("resourceType"))+ assertEquals("final", root.str("status"))+ assertEquals(+ "laboratory",+ (root["category"] as JsonArray).single().jsonObject["coding"]!!+ .jsonArray.single().jsonObject.str("code"),+ )+ val coding = root["code"]!!.jsonObject["coding"]!!.jsonArray.single().jsonObject+ assertEquals(FhirRecords.LOINC_SYSTEM, coding.str("system"))+ assertEquals("4548-4", coding.str("code"))++ val quantity = root["valueQuantity"]!!.jsonObject+ assertEquals("5.4", quantity.str("value"))+ assertEquals("%", quantity.str("unit"))+ assertEquals(FhirRecords.UCUM_SYSTEM, quantity.str("system"))++ val range = (root["referenceRange"] as JsonArray).single().jsonObject+ assertEquals("4.0", range["low"]!!.jsonObject.str("value"))+ assertEquals("5.6", range["high"]!!.jsonObject.str("value"))+ }++ @Test+ fun `a qualitative result becomes a string, not a zero`() {+ val qualitative = hba1c.copy(+ value = null,+ valueText = "Positive",+ unit = null,+ referenceLow = null,+ referenceHigh = null,+ )+ val root = parse(FhirRecords.labResultJson(qualitative))++ assertNull(root["valueQuantity"])+ assertEquals("Positive", root.str("valueString"))+ assertNull(root["referenceRange"])+ }++ @Test+ fun `a lab result round trips`() {+ val parsed = FhirRecords.parseLabResult(FhirRecords.labResultJson(hba1c), "src-1")++ assertNotNull(parsed)+ assertEquals(hba1c.loincCode, parsed.loincCode)+ assertEquals(hba1c.value, parsed.value)+ assertEquals(hba1c.unit, parsed.unit)+ assertEquals(hba1c.referenceLow, parsed.referenceLow)+ assertEquals(hba1c.referenceHigh, parsed.referenceHigh)+ assertEquals(hba1c.takenAt, parsed.takenAt)+ }++ @Test+ fun `out of range is derived from the result's own range`() {+ assert(!hba1c.isOutOfRange)+ assert(hba1c.copy(value = 7.2).isOutOfRange)+ assert(hba1c.copy(value = 3.1).isOutOfRange)+ // No range means nothing to be outside of, rather than everything being abnormal.+ assert(!hba1c.copy(value = 99.0, referenceLow = null, referenceHigh = null).isOutOfRange)+ }++ @Test+ fun `pregnancy status is a coded answer with an optional delivery date`() {+ val json = FhirRecords.pregnancyStatusJson(+ "obs-p",+ PregnancyStatus.Pregnant,+ Instant.parse("2026-03-04T00:00:00Z"),+ Instant.parse("2026-11-01T00:00:00Z"),+ )+ val root = parse(json)++ assertEquals(+ FhirRecords.LOINC_PREGNANCY_STATUS,+ root["code"]!!.jsonObject["coding"]!!.jsonArray.single().jsonObject.str("code"),+ )+ val value = root["valueCodeableConcept"]!!.jsonObject["coding"]!!+ .jsonArray.single().jsonObject+ assertEquals(FhirRecords.SNOMED_SYSTEM, value.str("system"))+ assertEquals("77386006", value.str("code"))++ val component = (root["component"] as JsonArray).single().jsonObject+ assertEquals("2026-11-01", component.str("valueDateTime"))++ val (status, due) = FhirRecords.parsePregnancyStatus(json)!!+ assertEquals(PregnancyStatus.Pregnant, status)+ assertEquals(Instant.parse("2026-11-01T00:00:00Z"), due)+ }++ @Test+ fun `not pregnant carries no delivery date`() {+ val json = FhirRecords.pregnancyStatusJson(+ "obs-p", PregnancyStatus.NotPregnant, Instant.parse("2026-03-04T00:00:00Z"), null+ )+ assertNull(parse(json)["component"])+ assertEquals(PregnancyStatus.NotPregnant, FhirRecords.parsePregnancyStatus(json)!!.first)+ }++ @Test+ fun `smoking status round trips through its SNOMED coding`() {+ for (status in SmokingStatus.entries) {+ val json = FhirRecords.smokingStatusJson(+ "obs-s", status, Instant.parse("2026-03-04T00:00:00Z")+ )+ assertEquals(status, FhirRecords.parseSmokingStatus(json), "for $status")+ }+ }++ @Test+ fun `the two profile observations are told apart by their LOINC code`() {+ val pregnancy = FhirRecords.pregnancyStatusJson(+ "a", PregnancyStatus.Pregnant, Instant.EPOCH, null+ )+ val smoking = FhirRecords.smokingStatusJson("b", SmokingStatus.Never, Instant.EPOCH)++ assertEquals(FhirRecords.LOINC_PREGNANCY_STATUS, FhirObservations.observationLoincCode(pregnancy))+ assertEquals(FhirRecords.LOINC_SMOKING_STATUS, FhirObservations.observationLoincCode(smoking))+ assertNull(FhirObservations.observationLoincCode(FhirRecords.conditionJson(diabetes)))+ }++ @Test+ fun `a provider lab result with a coded value rather than a number still parses`() {+ val provider = """+ {+ "resourceType": "Observation",+ "id": "provider-lab",+ "status": "final",+ "code": {+ "coding": [ { "system": "http://loinc.org", "code": "5811-5", "display": "Specific gravity of Urine" } ]+ },+ "subject": { "reference": "Patient/other" },+ "effectiveDateTime": "2025-12-01T09:00:00Z",+ "valueCodeableConcept": { "text": "Trace" }+ }+ """.trimIndent()++ val parsed = FhirRecords.parseLabResult(provider, "hospital")++ assertNotNull(parsed)+ assertEquals("5811-5", parsed.loincCode)+ assertNull(parsed.value)+ assertEquals("Trace", parsed.valueText)+ }++ // --- Helpers -------------------------------------------------------------++ @Test+ fun `parseQuantity only accepts a number followed by a unit`() {+ assertEquals(0.5 to "mL", FhirRecords.parseQuantity("0.5 mL"))+ assertEquals(2.0 to "tablets", FhirRecords.parseQuantity(" 2 tablets "))+ assertNull(FhirRecords.parseQuantity("one shot"))+ assertNull(FhirRecords.parseQuantity("0.5"))+ }++ @Test+ fun `parseDateTime accepts every precision FHIR allows`() {+ assertEquals(Instant.parse("2026-03-04T09:30:00Z"), FhirRecords.parseDateTime("2026-03-04T09:30:00Z"))+ assertEquals(Instant.parse("2026-03-04T00:00:00Z"), FhirRecords.parseDateTime("2026-03-04"))+ assertEquals(Instant.parse("2026-03-01T00:00:00Z"), FhirRecords.parseDateTime("2026-03"))+ assertEquals(Instant.parse("2026-01-01T00:00:00Z"), FhirRecords.parseDateTime("2026"))+ assertEquals(+ Instant.parse("2026-03-04T08:30:00Z"),+ FhirRecords.parseDateTime("2026-03-04T09:30:00+01:00"),+ )+ 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))+ }+}
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 5cc05764e7..46245dd843 100644--- a/health/src/test/java/com/vayunmathur/health/domain/FhirRecordsTest.kt+++ b/health/src/test/java/com/vayunmathur/health/domain/FhirRecordsTest.kt@@ -494,461 +494,4 @@ 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- fun `a provider resource with a date-only occurrence and no CVX still parses`() {- val provider = """- {- "resourceType": "Immunization",- "id": "provider-1",- "status": "completed",- "vaccineCode": {- "coding": [- { "system": "http://snomed.info/sct", "code": "1119349007", "display": "COVID-19 vaccine" }- ]- },- "patient": { "reference": "Patient/other" },- "occurrenceDateTime": "2021-04-19"- }- """.trimIndent()-- val parsed = FhirRecords.parseImmunization(provider, "hospital")-- assertNotNull(parsed)- assertNull(parsed.cvxCode)- assertEquals("COVID-19 vaccine", parsed.displayName)- assertEquals(Instant.parse("2021-04-19T00:00:00Z"), parsed.occurredAt)- }-- @Test- fun `unknown statuses are treated as still being taken`() {- val provider = """- {- "resourceType": "MedicationRequest",- "id": "provider-2",- "status": "unknown",- "intent": "order",- "medicationCodeableConcept": { "text": "Metformin" },- "subject": { "reference": "Patient/other" },- "authoredOn": "2024-06"- }- """.trimIndent()-- val parsed = FhirRecords.parseMedicationRequest(provider, "hospital")?.first-- assertNotNull(parsed)- assertEquals(MedicationStatus.Active, parsed.status)- assertEquals("Metformin", parsed.displayName)- assertEquals(Instant.parse("2024-06-01T00:00:00Z"), parsed.startedAt)- }-- @Test- fun `the wrong resource type and malformed json are refused, not thrown on`() {- assertNull(FhirRecords.parseImmunization("{ not json", "src"))- assertNull(FhirRecords.parseImmunization(FhirRecords.patientJson(), "src"))- assertNull(FhirRecords.parseMedicationRequest(FhirRecords.immunizationJson(flu), "src"))- }-- @Test- fun `the patient resource is minimal and well formed`() {- val root = parse(FhirRecords.patientJson())-- assertEquals("Patient", root.str("resourceType"))- assertEquals(FhirRecords.PATIENT_RESOURCE_ID, root.str("id"))- }-- // --- AllergyIntolerance ---------------------------------------------------- private val penicillin = AllergyEntry(- id = "alg-1",- rxcui = "7980",- displayName = "penicillin G",- category = AllergyCategory.Medication,- criticality = AllergyCriticality.High,- reaction = "anaphylaxis",- onsetAt = Instant.parse("2019-06-01T00:00:00Z"),- recordedAt = Instant.parse("2026-03-04T09:30:00Z"),- )-- @Test- fun `allergy carries the fields FHIR requires`() {- val root = parse(FhirRecords.allergyIntoleranceJson(penicillin))-- assertEquals("AllergyIntolerance", root.str("resourceType"))- assertEquals(- "Patient/${FhirRecords.PATIENT_RESOURCE_ID}",- root["patient"]!!.jsonObject.str("reference"),- )- assertEquals(- "active",- root["clinicalStatus"]!!.jsonObject["coding"]!!.jsonArray.single().jsonObject.str("code"),- )- assertEquals("high", root.str("criticality"))- assertEquals("medication", (root["category"] as JsonArray).single().jsonPrimitive.content)-- val coding = root["code"]!!.jsonObject["coding"]!!.jsonArray.single().jsonObject- assertEquals(FhirRecords.RXNORM_SYSTEM, coding.str("system"))- assertEquals("7980", coding.str("code"))- }-- @Test- fun `a food allergen has no coding but still has text`() {- val peanut = penicillin.copy(- rxcui = null,- displayName = "peanut",- category = AllergyCategory.Food,- )- val code = parse(FhirRecords.allergyIntoleranceJson(peanut))["code"]!!.jsonObject-- assertNull(code["coding"])- assertEquals("peanut", code.str("text"))- }-- @Test- fun `an unknown criticality is omitted rather than guessed`() {- val unknown = penicillin.copy(criticality = AllergyCriticality.Unknown)- assertNull(parse(FhirRecords.allergyIntoleranceJson(unknown))["criticality"])- }-- @Test- fun `an allergy round trips`() {- val parsed = FhirRecords.parseAllergyIntolerance(- FhirRecords.allergyIntoleranceJson(penicillin),- "src-1",- )-- assertNotNull(parsed)- assertEquals(penicillin.rxcui, parsed.rxcui)- assertEquals(penicillin.displayName, parsed.displayName)- assertEquals(penicillin.category, parsed.category)- assertEquals(penicillin.criticality, parsed.criticality)- assertEquals(penicillin.reaction, parsed.reaction)- assertEquals(penicillin.onsetAt, parsed.onsetAt)- assertEquals(penicillin.recordedAt, parsed.recordedAt)- }-- // --- Condition ------------------------------------------------------------- private val diabetes = ConditionEntry(- id = "cond-1",- icd10Code = "E11.9",- displayName = "Type 2 diabetes mellitus without complications",- status = ConditionStatus.Active,- onsetAt = Instant.parse("2022-01-15T00:00:00Z"),- )-- @Test- fun `condition carries the fields US Core requires`() {- val root = parse(FhirRecords.conditionJson(diabetes))-- assertEquals("Condition", root.str("resourceType"))- assertEquals(- "Patient/${FhirRecords.PATIENT_RESOURCE_ID}",- root["subject"]!!.jsonObject.str("reference"),- )- assertEquals(- "active",- root["clinicalStatus"]!!.jsonObject["coding"]!!.jsonArray.single().jsonObject.str("code"),- )- // US Core requires a category, and a user-maintained list is a problem list.- val category = (root["category"] as JsonArray).single().jsonObject- assertEquals(- "problem-list-item",- category["coding"]!!.jsonArray.single().jsonObject.str("code"),- )- assertEquals("2022-01-15", root.str("onsetDateTime"))-- val coding = root["code"]!!.jsonObject["coding"]!!.jsonArray.single().jsonObject- assertEquals(FhirRecords.ICD10_SYSTEM, coding.str("system"))- assertEquals("E11.9", coding.str("code"))- }-- @Test- fun `a resolved condition carries an abatement date`() {- val resolved = diabetes.copy(- status = ConditionStatus.Resolved,- resolvedAt = Instant.parse("2024-08-01T00:00:00Z"),- )- val root = parse(FhirRecords.conditionJson(resolved))-- assertEquals(- "resolved",- root["clinicalStatus"]!!.jsonObject["coding"]!!.jsonArray.single().jsonObject.str("code"),- )- assertEquals("2024-08-01", root.str("abatementDateTime"))- }-- @Test- fun `a condition round trips`() {- val parsed = FhirRecords.parseCondition(FhirRecords.conditionJson(diabetes), "src-1")-- assertNotNull(parsed)- assertEquals(diabetes.icd10Code, parsed.icd10Code)- assertEquals(diabetes.displayName, parsed.displayName)- assertEquals(diabetes.status, parsed.status)- assertEquals(diabetes.onsetAt, parsed.onsetAt)- }-- @Test- fun `a provider condition dated only by period still parses`() {- val provider = """- {- "resourceType": "Condition",- "id": "provider-3",- "clinicalStatus": { "coding": [ { "code": "inactive" } ] },- "code": { "text": "Asthma" },- "subject": { "reference": "Patient/other" },- "onsetPeriod": { "start": "2015-04-01" }- }- """.trimIndent()-- val parsed = FhirRecords.parseCondition(provider, "hospital")-- assertNotNull(parsed)- assertEquals("Asthma", parsed.displayName)- assertEquals(ConditionStatus.Resolved, parsed.status)- assertEquals(Instant.parse("2015-04-01T00:00:00Z"), parsed.onsetAt)- }-- @Test- fun `the allergy and condition parsers refuse each other's resources`() {- val allergy = FhirRecords.allergyIntoleranceJson(penicillin)- val condition = FhirRecords.conditionJson(diabetes)-- assertNull(FhirRecords.parseCondition(allergy, "src"))- assertNull(FhirRecords.parseAllergyIntolerance(condition, "src"))- }-- // --- Observations ---------------------------------------------------------- private val hba1c = LabResultEntry(- id = "lab-1",- loincCode = "4548-4",- displayName = "Hemoglobin A1c/Hemoglobin.total in Blood",- value = 5.4,- unit = "%",- referenceLow = 4.0,- referenceHigh = 5.6,- takenAt = Instant.parse("2026-02-11T08:15:00Z"),- )-- @Test- fun `a numeric lab result carries a quantity and its reference range`() {- val root = parse(FhirRecords.labResultJson(hba1c))-- assertEquals("Observation", root.str("resourceType"))- assertEquals("final", root.str("status"))- assertEquals(- "laboratory",- (root["category"] as JsonArray).single().jsonObject["coding"]!!- .jsonArray.single().jsonObject.str("code"),- )- val coding = root["code"]!!.jsonObject["coding"]!!.jsonArray.single().jsonObject- assertEquals(FhirRecords.LOINC_SYSTEM, coding.str("system"))- assertEquals("4548-4", coding.str("code"))-- val quantity = root["valueQuantity"]!!.jsonObject- assertEquals("5.4", quantity.str("value"))- assertEquals("%", quantity.str("unit"))- assertEquals(FhirRecords.UCUM_SYSTEM, quantity.str("system"))-- val range = (root["referenceRange"] as JsonArray).single().jsonObject- assertEquals("4.0", range["low"]!!.jsonObject.str("value"))- assertEquals("5.6", range["high"]!!.jsonObject.str("value"))- }-- @Test- fun `a qualitative result becomes a string, not a zero`() {- val qualitative = hba1c.copy(- value = null,- valueText = "Positive",- unit = null,- referenceLow = null,- referenceHigh = null,- )- val root = parse(FhirRecords.labResultJson(qualitative))-- assertNull(root["valueQuantity"])- assertEquals("Positive", root.str("valueString"))- assertNull(root["referenceRange"])- }-- @Test- fun `a lab result round trips`() {- val parsed = FhirRecords.parseLabResult(FhirRecords.labResultJson(hba1c), "src-1")-- assertNotNull(parsed)- assertEquals(hba1c.loincCode, parsed.loincCode)- assertEquals(hba1c.value, parsed.value)- assertEquals(hba1c.unit, parsed.unit)- assertEquals(hba1c.referenceLow, parsed.referenceLow)- assertEquals(hba1c.referenceHigh, parsed.referenceHigh)- assertEquals(hba1c.takenAt, parsed.takenAt)- }-- @Test- fun `out of range is derived from the result's own range`() {- assert(!hba1c.isOutOfRange)- assert(hba1c.copy(value = 7.2).isOutOfRange)- assert(hba1c.copy(value = 3.1).isOutOfRange)- // No range means nothing to be outside of, rather than everything being abnormal.- assert(!hba1c.copy(value = 99.0, referenceLow = null, referenceHigh = null).isOutOfRange)- }-- @Test- fun `pregnancy status is a coded answer with an optional delivery date`() {- val json = FhirRecords.pregnancyStatusJson(- "obs-p",- PregnancyStatus.Pregnant,- Instant.parse("2026-03-04T00:00:00Z"),- Instant.parse("2026-11-01T00:00:00Z"),- )- val root = parse(json)-- assertEquals(- FhirRecords.LOINC_PREGNANCY_STATUS,- root["code"]!!.jsonObject["coding"]!!.jsonArray.single().jsonObject.str("code"),- )- val value = root["valueCodeableConcept"]!!.jsonObject["coding"]!!- .jsonArray.single().jsonObject- assertEquals(FhirRecords.SNOMED_SYSTEM, value.str("system"))- assertEquals("77386006", value.str("code"))-- val component = (root["component"] as JsonArray).single().jsonObject- assertEquals("2026-11-01", component.str("valueDateTime"))-- val (status, due) = FhirRecords.parsePregnancyStatus(json)!!- assertEquals(PregnancyStatus.Pregnant, status)- assertEquals(Instant.parse("2026-11-01T00:00:00Z"), due)- }-- @Test- fun `not pregnant carries no delivery date`() {- val json = FhirRecords.pregnancyStatusJson(- "obs-p", PregnancyStatus.NotPregnant, Instant.parse("2026-03-04T00:00:00Z"), null- )- assertNull(parse(json)["component"])- assertEquals(PregnancyStatus.NotPregnant, FhirRecords.parsePregnancyStatus(json)!!.first)- }-- @Test- fun `smoking status round trips through its SNOMED coding`() {- for (status in SmokingStatus.entries) {- val json = FhirRecords.smokingStatusJson(- "obs-s", status, Instant.parse("2026-03-04T00:00:00Z")- )- assertEquals(status, FhirRecords.parseSmokingStatus(json), "for $status")- }- }-- @Test- fun `the two profile observations are told apart by their LOINC code`() {- val pregnancy = FhirRecords.pregnancyStatusJson(- "a", PregnancyStatus.Pregnant, Instant.EPOCH, null- )- val smoking = FhirRecords.smokingStatusJson("b", SmokingStatus.Never, Instant.EPOCH)-- assertEquals(FhirRecords.LOINC_PREGNANCY_STATUS, FhirRecords.observationLoincCode(pregnancy))- assertEquals(FhirRecords.LOINC_SMOKING_STATUS, FhirRecords.observationLoincCode(smoking))- assertNull(FhirRecords.observationLoincCode(FhirRecords.conditionJson(diabetes)))- }-- @Test- fun `a provider lab result with a coded value rather than a number still parses`() {- val provider = """- {- "resourceType": "Observation",- "id": "provider-lab",- "status": "final",- "code": {- "coding": [ { "system": "http://loinc.org", "code": "5811-5", "display": "Specific gravity of Urine" } ]- },- "subject": { "reference": "Patient/other" },- "effectiveDateTime": "2025-12-01T09:00:00Z",- "valueCodeableConcept": { "text": "Trace" }- }- """.trimIndent()-- val parsed = FhirRecords.parseLabResult(provider, "hospital")-- assertNotNull(parsed)- assertEquals("5811-5", parsed.loincCode)- assertNull(parsed.value)- assertEquals("Trace", parsed.valueText)- }-- // --- Helpers --------------------------------------------------------------- @Test- fun `parseQuantity only accepts a number followed by a unit`() {- assertEquals(0.5 to "mL", FhirRecords.parseQuantity("0.5 mL"))- assertEquals(2.0 to "tablets", FhirRecords.parseQuantity(" 2 tablets "))- assertNull(FhirRecords.parseQuantity("one shot"))- assertNull(FhirRecords.parseQuantity("0.5"))- }-- @Test- fun `parseDateTime accepts every precision FHIR allows`() {- assertEquals(Instant.parse("2026-03-04T09:30:00Z"), FhirRecords.parseDateTime("2026-03-04T09:30:00Z"))- assertEquals(Instant.parse("2026-03-04T00:00:00Z"), FhirRecords.parseDateTime("2026-03-04"))- assertEquals(Instant.parse("2026-03-01T00:00:00Z"), FhirRecords.parseDateTime("2026-03"))- assertEquals(Instant.parse("2026-01-01T00:00:00Z"), FhirRecords.parseDateTime("2026"))- assertEquals(- Instant.parse("2026-03-04T08:30:00Z"),- FhirRecords.parseDateTime("2026-03-04T09:30:00+01:00"),- )- 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))- } }
health/src/test/java/com/vayunmathur/health/domain/SocialHistoryQuestionsTest.kt
diff --git a/health/src/test/java/com/vayunmathur/health/domain/SocialHistoryQuestionsTest.kt b/health/src/test/java/com/vayunmathur/health/domain/SocialHistoryQuestionsTest.ktindex 2ab9c4920b..e1740f5433 100644--- a/health/src/test/java/com/vayunmathur/health/domain/SocialHistoryQuestionsTest.kt+++ b/health/src/test/java/com/vayunmathur/health/domain/SocialHistoryQuestionsTest.kt@@ -94,12 +94,12 @@ class SocialHistoryQuestionsTest { assertEquals( question.loinc,- FhirRecords.observationLoincCode(json),+ FhirObservations.observationLoincCode(json), "question code lost for ${question.loinc}", ) assertEquals( answer.code,- FhirRecords.parseSocialHistoryAnswer(json),+ FhirObservations.parseSocialHistoryAnswer(json), "answer code lost for ${answer.code}", ) }@@ -158,13 +158,13 @@ class SocialHistoryQuestionsTest { "Often true", value["coding"]!!.jsonArray.single().jsonObject.str("display"), )- assertEquals("LA28397-0", FhirRecords.parseSocialHistoryAnswer(json))+ assertEquals("LA28397-0", FhirObservations.parseSocialHistoryAnswer(json)) } @Test fun `a non observation is not mistaken for an answer`() {- assertNull(FhirRecords.parseSocialHistoryAnswer("""{"resourceType":"Condition"}"""))- assertNull(FhirRecords.parseSocialHistoryAnswer("not json at all"))+ assertNull(FhirObservations.parseSocialHistoryAnswer("""{"resourceType":"Condition"}"""))+ assertNull(FhirObservations.parseSocialHistoryAnswer("not json at all")) } @Test@@ -177,8 +177,8 @@ class SocialHistoryQuestionsTest { } """.trimIndent() - assertEquals("68518-0", FhirRecords.observationLoincCode(bare))- assertNull(FhirRecords.parseSocialHistoryAnswer(bare))+ assertEquals("68518-0", FhirObservations.observationLoincCode(bare))+ assertNull(FhirObservations.parseSocialHistoryAnswer(bare)) } @Test
health/src/test/java/com/vayunmathur/health/ui/AboutYouDialogsTest.kt
diff --git a/health/src/test/java/com/vayunmathur/health/ui/AboutYouDialogsTest.kt b/health/src/test/java/com/vayunmathur/health/ui/AboutYouDialogsTest.ktindex f6220fd22b..7149beba6a 100644--- a/health/src/test/java/com/vayunmathur/health/ui/AboutYouDialogsTest.kt+++ b/health/src/test/java/com/vayunmathur/health/ui/AboutYouDialogsTest.kt@@ -65,7 +65,7 @@ class AboutYouDialogsTest { rule.waitForIdle() } - private fun settleProfile(vm: MedicalViewModel, cond: () -> Boolean) {+ private fun settleProfile(cond: () -> Boolean) { repeat(100) { rule.waitForIdle() if (cond()) return@@ -84,7 +84,7 @@ class AboutYouDialogsTest { rule.onAllNodesWithText(label, substring = false).fetchSemanticsNodes().let { nodes -> rule.onAllNodesWithText(label, substring = false)[nodes.size - 1].performClick() }- settleProfile(vm) { vm.profile.value.smokingStatus == SmokingStatus.entries.last() }+ settleProfile { vm.profile.value.smokingStatus == SmokingStatus.entries.last() } assertEquals(SmokingStatus.entries.last(), HealthRepository.get(context).getProfile()?.smokingStatus) } @@ -98,7 +98,7 @@ class AboutYouDialogsTest { rule.onAllNodesWithText(label, substring = false).fetchSemanticsNodes().let { nodes -> rule.onAllNodesWithText(label, substring = false)[nodes.size - 1].performClick() }- settleProfile(vm) { vm.profile.value.pregnancyStatus == PregnancyStatus.Pregnant }+ settleProfile { vm.profile.value.pregnancyStatus == PregnancyStatus.Pregnant } assertEquals(PregnancyStatus.Pregnant, HealthRepository.get(context).getProfile()?.pregnancyStatus) }
health/src/test/java/com/vayunmathur/health/util/FhirRecordsGapsTest.kt
diff --git a/health/src/test/java/com/vayunmathur/health/util/FhirRecordsGapsTest.kt b/health/src/test/java/com/vayunmathur/health/util/FhirRecordsGapsTest.ktindex a3a8cb60be..0ff7d32ff1 100644--- a/health/src/test/java/com/vayunmathur/health/util/FhirRecordsGapsTest.kt+++ b/health/src/test/java/com/vayunmathur/health/util/FhirRecordsGapsTest.kt@@ -14,6 +14,7 @@ import com.vayunmathur.health.data.PregnancyStatus import com.vayunmathur.health.data.RepeatUnit import com.vayunmathur.health.data.SmokingStatus import com.vayunmathur.health.data.VaccinationEntry+import com.vayunmathur.health.domain.FhirObservations import com.vayunmathur.health.domain.FhirRecords import com.vayunmathur.health.domain.SocialHistoryQuestions import java.time.Instant@@ -528,17 +529,17 @@ class FhirRecordsGapsTest { @Test fun `resource id and effective instant read through`() {- assertEquals("x-1", FhirRecords.resourceId("""{"id":"x-1"}"""))- assertNull(FhirRecords.resourceId("not json"))+ assertEquals("x-1", FhirObservations.resourceId("""{"id":"x-1"}"""))+ assertNull(FhirObservations.resourceId("not json")) assertEquals( Instant.parse("2025-11-02T10:00:00Z"),- FhirRecords.observationEffective("""{"effectiveDateTime":"2025-11-02T10:00:00Z"}"""),+ FhirObservations.observationEffective("""{"effectiveDateTime":"2025-11-02T10:00:00Z"}"""), ) assertEquals( Instant.parse("2025-11-02T00:00:00Z"),- FhirRecords.observationEffective("""{"effectivePeriod":{"start":"2025-11-02"}}"""),+ FhirObservations.observationEffective("""{"effectivePeriod":{"start":"2025-11-02"}}"""), )- assertNull(FhirRecords.observationEffective("""{"resourceType":"Observation"}"""))+ assertNull(FhirObservations.observationEffective("""{"resourceType":"Observation"}""")) } @Test@@ -579,6 +580,6 @@ class FhirRecordsGapsTest { val json = FhirRecords.socialHistoryAnswerJson("o", question, answer, t) assertTrue(question.loinc in json) assertTrue(answer.code in json)- assertEquals("o", FhirRecords.resourceId(json))+ assertEquals("o", FhirObservations.resourceId(json)) } }
health/src/test/java/com/vayunmathur/health/util/HealthChartData2Test.kt
diff --git a/health/src/test/java/com/vayunmathur/health/util/HealthChartData2Test.kt b/health/src/test/java/com/vayunmathur/health/util/HealthChartData2Test.ktindex 51c1acbe4c..3eb46db597 100644--- a/health/src/test/java/com/vayunmathur/health/util/HealthChartData2Test.kt+++ b/health/src/test/java/com/vayunmathur/health/util/HealthChartData2Test.kt@@ -79,17 +79,17 @@ class HealthChartData2Test { Tuple3(LocalDate(2024, 6, 3).toEpochDays().toLong(), 100.0, 50.0), Tuple3(LocalDate(2024, 6, 4).toEpochDays().toLong(), 200.0, 60.0), )- val week = HealthChartData.buildHistoryItems(HealthMetricConfig.STEPS, 1, LocalDate(2024, 6, 2), start, tz, resources, weekPairs)+ val week = HealthChartData.buildHistoryItems(HealthMetricConfig.STEPS, 1, LocalDate(2024, 6, 2), resources, weekPairs) assertEquals(7, week.size) assertTrue(week.any { it.value == 200.0 })- val weekLine = HealthChartData.buildHistoryItems(HealthMetricConfig.HEART_RATE, 1, LocalDate(2024, 6, 2), start, tz, resources, weekPairs)+ val weekLine = HealthChartData.buildHistoryItems(HealthMetricConfig.HEART_RATE, 1, LocalDate(2024, 6, 2), resources, weekPairs) assertTrue(weekLine.size <= 7)- val month = HealthChartData.buildHistoryItems(HealthMetricConfig.BLOOD_PRESSURE, 2, LocalDate(2024, 6, 1), start, tz, resources, pairs)+ val month = HealthChartData.buildHistoryItems(HealthMetricConfig.BLOOD_PRESSURE, 2, LocalDate(2024, 6, 1), resources, pairs) assertEquals(2, month.size) assertEquals(50.0, month.last().secondaryValue)- val year = HealthChartData.buildHistoryItems(HealthMetricConfig.STEPS, 3, LocalDate(2024, 1, 1), start, tz, resources, pairs)+ val year = HealthChartData.buildHistoryItems(HealthMetricConfig.STEPS, 3, LocalDate(2024, 1, 1), resources, pairs) assertEquals(2, year.size)- val day = HealthChartData.buildHistoryItems(HealthMetricConfig.STEPS, 0, LocalDate(2024, 6, 2), start, tz, resources, pairs)+ val day = HealthChartData.buildHistoryItems(HealthMetricConfig.STEPS, 0, LocalDate(2024, 6, 2), resources, pairs) assertTrue(day.isEmpty()) }
health/src/test/java/com/vayunmathur/health/util/HealthChartDataTest.kt
diff --git a/health/src/test/java/com/vayunmathur/health/util/HealthChartDataTest.kt b/health/src/test/java/com/vayunmathur/health/util/HealthChartDataTest.ktindex be36f66037..879a2ba401 100644--- a/health/src/test/java/com/vayunmathur/health/util/HealthChartDataTest.kt+++ b/health/src/test/java/com/vayunmathur/health/util/HealthChartDataTest.kt@@ -189,8 +189,7 @@ class HealthChartDataTest { val monday = LocalDate(2026, 3, 2) val history = HealthChartData.buildHistoryItems( HealthMetricConfig.STEPS, 1, weekStart,- kotlin.time.Instant.fromEpochMilliseconds(0),- TimeZone.currentSystemDefault(), context.resources,+ context.resources, listOf(Tuple3(monday.toEpochDays().toLong(), 12_000.0, 0.0)), ) assertEquals(7, history.size)@@ -203,8 +202,7 @@ class HealthChartDataTest { fun `day tab builds no history rows`() { val history = HealthChartData.buildHistoryItems( HealthMetricConfig.STEPS, 0, LocalDate(2026, 3, 4),- kotlin.time.Instant.fromEpochMilliseconds(0),- TimeZone.currentSystemDefault(), context.resources,+ context.resources, listOf(Tuple3(0L, 100.0, 0.0)), ) assertTrue(history.isEmpty())