health: profile import keeps the newest standing status, not the last-listed
- Commit
2eaef19eb8a49f5f36a03aa98d1ec7d199d32207- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-01 07:48 UTC (5 days ago)
- Parents
0902d7a
importProfile documents 'only the newest of each is kept' but applied every pregnancy/smoking resource in list order, so the final value was whichever observation the Health Connect page happened to list last — and readAll returns raw page order with no date sort. Newest-first inputs (Current@2026-06-01 then Never@2025-01-01) imported as Never; a provider's older observation listed last could also revert a status the user had just set locally. The social-history branch in the same function already selected newest and guarded newer local answers; the standing-status branch never read the observations' dates at all. Each observation is now a dated candidate (undated sorts oldest); only the newest applies, and only when it is not older than the locally recorded status, stamping recordedAt/FHIR id from the winner. Two regression tests failed pre-fix. Chart aggregation, DAO ranges, unit scaling and dose scheduling were audited and cleared. Verified: :health:testDevUnitTest 652 tests pass; lint errors are pre-existing on untouched files.
Diff
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 c2aaccba6b..290f755170 100644--- a/health/src/main/java/com/vayunmathur/health/platform/MedicalImportOps.kt+++ b/health/src/main/java/com/vayunmathur/health/platform/MedicalImportOps.kt@@ -7,11 +7,14 @@ 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.PregnancyStatus import com.vayunmathur.health.data.ProfileAnswer+import com.vayunmathur.health.data.SmokingStatus import com.vayunmathur.health.domain.FhirObservations import com.vayunmathur.health.domain.FhirRecords import com.vayunmathur.health.domain.SocialHistoryQuestions import kotlinx.coroutines.launch+import java.time.Instant import java.util.UUID /**@@ -319,15 +322,49 @@ private suspend fun MedicalViewModel.importProfile() { // appears to revert after being set. val newest = mutableMapOf<String, ProfileAnswer>() + // The two standing statuses get the same treatment as the answers below:+ // keep the newest by the observation's own date, never whichever the+ // category read happened to list last. readAll returns Health Connect's+ // page order, which is not date order, so applying every resource in+ // sequence let an older provider observation revert a newer answer.+ var pregnancy: PregnancyCandidate? = null+ var smoking: SmokingCandidate? = null+ resources.forEach { resource -> 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 }+ FhirRecords.LOINC_PREGNANCY_STATUS ->+ pregnancy = newerOf(pregnancy, parsePregnancy(resource))+ FhirRecords.LOINC_SMOKING_STATUS ->+ smoking = newerOf(smoking, parseSmoking(resource)) else -> applySocialHistoryAnswer(resource, loinc, newest) } } + // Never overwrite a newer local answer, matching the ProfileAnswer guard+ // below: the user may have just set a status while this import was reading.+ pregnancy?.let { candidate ->+ val localAt = profile.pregnancyRecordedAt+ if (localAt == null || !candidate.effectiveOrEpoch.isBefore(localAt)) {+ profile = profile.copy(+ pregnancyStatus = candidate.status,+ dueDate = candidate.dueDate,+ pregnancyRecordedAt = candidate.effective ?: profile.pregnancyRecordedAt,+ pregnancyFhirId = candidate.fhirId ?: profile.pregnancyFhirId,+ )+ }+ }+ smoking?.let { candidate ->+ val localAt = profile.smokingRecordedAt+ if (localAt == null || !candidate.effectiveOrEpoch.isBefore(localAt)) {+ profile = profile.copy(+ smokingStatus = candidate.status,+ smokingRecordedAt = candidate.effective ?: profile.smokingRecordedAt,+ smokingFhirId = candidate.fhirId ?: profile.smokingFhirId,+ )+ }+ }+ newest.values.forEach { incoming -> val local = repository.getProfileAnswer(incoming.loincCode) // Never overwrite a newer local answer. The user may have just tapped one while this@@ -339,30 +376,67 @@ private suspend fun MedicalViewModel.importProfile() { repository.upsertProfile(profile) } -private fun MedicalViewModel.applyPregnancy(+/** A pregnancy observation reduced to what the profile keeps, with its date. */+private data class PregnancyCandidate(+ val status: PregnancyStatus,+ val dueDate: Instant?,+ val effective: Instant?,+ val fhirId: String?,+) {+ /** Undated observations sort as oldest, so a dated one always wins. */+ val effectiveOrEpoch: Instant get() = effective ?: Instant.EPOCH+}++/** A smoking observation reduced to what the profile keeps, with its date. */+private data class SmokingCandidate(+ val status: SmokingStatus,+ val effective: Instant?,+ val fhirId: String?,+) {+ /** Undated observations sort as oldest, so a dated one always wins. */+ val effectiveOrEpoch: Instant get() = effective ?: Instant.EPOCH+}++private fun parsePregnancy( resource: PersonalHealthRecords.RawResource,- profile: HealthProfile,-): HealthProfile =+): PregnancyCandidate? = FhirRecords.parsePregnancyStatus(resource.data)?.let { (status, due) ->- profile.copy(- pregnancyStatus = status,+ PregnancyCandidate(+ status = status, dueDate = due,- pregnancyFhirId = profile.pregnancyFhirId- ?: FhirObservations.resourceId(resource.data),+ effective = FhirObservations.observationEffective(resource.data),+ fhirId = FhirObservations.resourceId(resource.data), )- } ?: profile+ } -private fun MedicalViewModel.applySmoking(+private fun parseSmoking( resource: PersonalHealthRecords.RawResource,- profile: HealthProfile,-): HealthProfile =+): SmokingCandidate? = FhirRecords.parseSmokingStatus(resource.data)?.let { status ->- profile.copy(- smokingStatus = status,- smokingFhirId = profile.smokingFhirId- ?: FhirObservations.resourceId(resource.data),+ SmokingCandidate(+ status = status,+ effective = FhirObservations.observationEffective(resource.data),+ fhirId = FhirObservations.resourceId(resource.data), )- } ?: profile+ }++/** The newer of two parsed pregnancy observations; a tie keeps the later-listed one. */+private fun newerOf(held: PregnancyCandidate?, candidate: PregnancyCandidate?): PregnancyCandidate? =+ when {+ candidate == null -> held+ held == null -> candidate+ candidate.effectiveOrEpoch.isBefore(held.effectiveOrEpoch) -> held+ else -> candidate+ }++/** The newer of two parsed smoking observations; a tie keeps the later-listed one. */+private fun newerOf(held: SmokingCandidate?, candidate: SmokingCandidate?): SmokingCandidate? =+ when {+ candidate == null -> held+ held == null -> candidate+ candidate.effectiveOrEpoch.isBefore(held.effectiveOrEpoch) -> held+ else -> candidate+ } private fun MedicalViewModel.applySocialHistoryAnswer( resource: PersonalHealthRecords.RawResource,
health/src/test/java/com/vayunmathur/health/platform/MedicalImportC5Test.kt
diff --git a/health/src/test/java/com/vayunmathur/health/platform/MedicalImportC5Test.kt b/health/src/test/java/com/vayunmathur/health/platform/MedicalImportC5Test.ktindex b28d0b5884..4bf31c5673 100644--- a/health/src/test/java/com/vayunmathur/health/platform/MedicalImportC5Test.kt+++ b/health/src/test/java/com/vayunmathur/health/platform/MedicalImportC5Test.kt@@ -460,6 +460,76 @@ class MedicalImportC5Test { assertEquals(answer.code, stored.answerCode) } + @Test+ fun `profile import keeps newest standing status regardless of list order`() = runTest {+ // Newest first, older second: the category read's list order must not+ // let the stale observation listed last win (regression: importProfile+ // applied every pregnancy/smoking resource in sequence).+ val newer = Instant.parse("2026-06-01T09:30:00Z")+ val older = Instant.parse("2025-01-01T09:30:00Z")+ // The profile is a singleton in a database shared across this class,+ // so start and end from a clean one to stay order-independent.+ repository().upsertProfile(com.vayunmathur.health.data.HealthProfile())+ client.add(+ PersonalHealthRecords.pregnancyType, PersonalHealthRecords.observationResourceType,+ hospital, "preg-new",+ FhirRecords.pregnancyStatusJson(+ "preg-new", com.vayunmathur.health.data.PregnancyStatus.Pregnant, newer, null,+ ),+ )+ client.add(+ PersonalHealthRecords.pregnancyType, PersonalHealthRecords.observationResourceType,+ hospital, "preg-old",+ FhirRecords.pregnancyStatusJson(+ "preg-old", com.vayunmathur.health.data.PregnancyStatus.NotPregnant, older, null,+ ),+ )+ client.add(+ PersonalHealthRecords.socialHistoryType, PersonalHealthRecords.observationResourceType,+ hospital, "smoke-new",+ FhirRecords.smokingStatusJson("smoke-new", SmokingStatus.Current, newer),+ )+ client.add(+ PersonalHealthRecords.socialHistoryType, PersonalHealthRecords.observationResourceType,+ hospital, "smoke-old",+ FhirRecords.smokingStatusJson("smoke-old", SmokingStatus.Never, older),+ )+ val repo = repository()+ import()+ settle { repo.getProfile()?.smokingStatus == SmokingStatus.Current }+ assertEquals(+ com.vayunmathur.health.data.PregnancyStatus.Pregnant,+ repo.getProfile()?.pregnancyStatus,+ )+ assertEquals(newer, repo.getProfile()?.pregnancyRecordedAt)+ assertEquals(newer, repo.getProfile()?.smokingRecordedAt)+ repo.upsertProfile(com.vayunmathur.health.data.HealthProfile())+ }++ @Test+ fun `profile import does not overwrite a newer local standing status`() = runTest {+ val localAt = Instant.parse("2026-06-01T09:30:00Z")+ val older = Instant.parse("2025-01-01T09:30:00Z")+ val repo = repository()+ repo.upsertProfile(+ com.vayunmathur.health.data.HealthProfile(+ smokingStatus = SmokingStatus.Current,+ smokingRecordedAt = localAt,+ ),+ )+ client.add(+ PersonalHealthRecords.socialHistoryType, PersonalHealthRecords.observationResourceType,+ hospital, "smoke-stale",+ FhirRecords.smokingStatusJson("smoke-stale", SmokingStatus.Never, older),+ )+ val vm = viewModel()+ vm.importFromHealthConnect()+ settle { !vm.syncing.value }+ assertEquals(SmokingStatus.Current, repo.getProfile()?.smokingStatus)+ assertEquals(localAt, repo.getProfile()?.smokingRecordedAt)+ repo.upsertProfile(com.vayunmathur.health.data.HealthProfile())+ }+ @Test fun `pending mirrors and remote deletes are pushed before import`() = runTest { val repo = repository()