health: social history questions, and fix answers not sticking
- Commit
e297fa9f5f20bd701e6fdff78d517ac8fedcc0e0- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-12 02:24 UTC (2 months ago)
- Parents
7dbf5e7
Adds the rest of what C-CDA calls social history - alcohol, drug use,
housing, the two Hunger Vital Sign questions and transport - alongside
the pregnancy and smoking status already on the About you screen.
Question and answer codes were read out of the LOINC 2.83 release rather
than recalled; several plausible guesses turned out to be wrong. 11331-6
and 96842-8 carry no answer list at all, 68517-2 is a drinks question
rather than the NIDA screen, and 93031-3 asks about unmet needs, not
hunger. analysis/loinc_answers.py is how they were checked.
Each question is stored as a ProfileAnswer row keyed by its LOINC code
rather than as more columns on the profile, since occupation, industry
and environmental factors are still to come. Smoking and pregnancy stay
as their own fields because both have US Core profiles bound to SNOMED
rather than to a LOINC answer list.
Questions are shown in full. They are validated instruments whose wording
is the measurement - shortening one to a topic drops the time window and
the qualifying clause, and no answer wording recovers that.
Fixes an answer sometimes reverting after being set: importProfile wrote
rows without fhirResourceId, so the next answer minted a fresh id and
wrote a second observation instead of updating the first. Import then saw
several answers to one question and took whichever came last. The id is
now preserved, the newest observation wins on its own effectiveDateTime,
and an import never overwrites a locally newer answer.
Fixes labs finding nothing: the fast path in ReferenceCatalog.prepare
short-circuited on schema version alone, so a database built at the same
schema without the LOINC table was never replaced. It now compares the
whole descriptor before taking the fast path.
Also removes the two-character search minimum, which made a single letter
look broken to save 10ms off the main thread, and the last reload button.
Test Plan:
65 unit tests pass, including 12 new ones guarding the LOINC codes:
gradlew :health:testDevUnitTest
DoseScheduleTest: tests=19 failures=0
FhirRecordsTest: tests=34 failures=0
SocialHistoryQuestionsTest: tests=12 failures=0
Lint clean for health. Installed on a Pixel 9 Pro XL and confirmed the
catalogue re-unpacked with the LOINC table present:
adb shell run-as com.vayunmathur.health cat files/catalog.db.meta.json
{"schemaVersion":4,...,"labs":62138,...}Diff
health/src/main/java/com/vayunmathur/health/data/HealthRepository.kt
diff --git a/health/src/main/java/com/vayunmathur/health/data/HealthRepository.kt b/health/src/main/java/com/vayunmathur/health/data/HealthRepository.ktindex 5bfc7ed433..cfd0325b43 100644--- a/health/src/main/java/com/vayunmathur/health/data/HealthRepository.kt+++ b/health/src/main/java/com/vayunmathur/health/data/HealthRepository.kt@@ -124,6 +124,7 @@ class HealthRepository private constructor(context: Context) : fun getProfileAnswersFlow(): Flow<List<ProfileAnswer>> = medicalDao.getProfileAnswersFlow() suspend fun getProfileAnswer(loincCode: String): ProfileAnswer? = medicalDao.getProfileAnswer(loincCode)+ suspend fun deleteProfileAnswer(loincCode: String) = medicalDao.deleteProfileAnswer(loincCode) /** Expose underlying [HealthDatabase] for call sites that need transactional access (prefer adding a method here instead). */ internal val database: HealthDatabase get() = db
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 6c78170a5f..38db53012e 100644--- a/health/src/main/java/com/vayunmathur/health/data/MedicalRecords.kt+++ b/health/src/main/java/com/vayunmathur/health/data/MedicalRecords.kt@@ -350,4 +350,7 @@ interface MedicalDao { @Query("SELECT * FROM ProfileAnswer WHERE loincCode = :loincCode") suspend fun getProfileAnswer(loincCode: String): ProfileAnswer?++ @Query("DELETE FROM ProfileAnswer WHERE loincCode = :loincCode")+ suspend fun deleteProfileAnswer(loincCode: String) }
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 26cc149250..60f728ad72 100644--- a/health/src/main/java/com/vayunmathur/health/data/ReferenceCatalog.kt+++ b/health/src/main/java/com/vayunmathur/health/data/ReferenceCatalog.kt@@ -137,6 +137,17 @@ object ReferenceCatalog { private val prepareMutex = Mutex() + /**+ * The unpacked database, once confirmed to match the asset in this process.+ *+ * Confirmation is what makes [prepare] cheap to call on every picker, and it deliberately+ * compares the whole descriptor rather than just [Meta.schemaVersion]. Two builds can share a+ * schema and hold different data — adding the LOINC table did exactly that — and short-cutting+ * on the version alone leaves the previous build's database in place forever.+ */+ @Volatile+ private var verified: Meta? = null+ private var handle: SQLiteDatabase? = null private val lock = Any() @@ -152,7 +163,6 @@ object ReferenceCatalog { // rather than leaving a few megabytes of dead database in filesDir forever. File(appContext.filesDir, "rxterms.db").delete() File(appContext.filesDir, "rxterms.db.meta.json").delete()- installedMeta()?.let { _status.value = Status.Ready(it) } } /**@@ -380,10 +390,10 @@ object ReferenceCatalog { * was typed, and "type 2 diab" likewise. A search box that is empty for seven of the eight * keystrokes it takes to reach a result reads as broken, and no amount of making it faster helps. *- * Returns null below [MIN_QUERY_LENGTH] characters as well as for input with nothing searchable- * in it. A one-letter prefix matches tens of thousands of rows, and while finding them is cheap- * the sort to rank them is not — measured at 10 ms against 0.3 ms for three letters. One letter- * is not a search, so the cheapest fix is to decline it.+ * One character is searched like any other. A single-letter prefix does cost more — about 10 ms+ * against the conditions table, almost all of it ranking the matches rather than finding them,+ * versus 0.3 ms from three letters on. That is off the main thread and behind a debounce, so it+ * is invisible; an empty list after typing a letter is not. * * Splitting on everything non-alphanumeric matches how the unicode61 tokenizer split the indexed * text; quoting stops `-`, `(` and `*` in the user's own input being read as operators, and one@@ -391,14 +401,10 @@ object ReferenceCatalog { * index cannot evaluate. Space-separated terms keep FTS5's implicit AND. */ internal fun escapeFtsQuery(raw: String): String? {- if (raw.trim().length < MIN_QUERY_LENGTH) return null val tokens = raw.split(Regex("[^\\p{L}\\p{N}]+")).filter { it.isNotEmpty() } return if (tokens.isEmpty()) null else tokens.joinToString(" ") { "\"$it\"*" } } - /** Shortest input worth querying the database for. See [escapeFtsQuery]. */- const val MIN_QUERY_LENGTH = 2- // --- Unpacking --------------------------------------------------------- /**@@ -406,12 +412,13 @@ object ReferenceCatalog { * screen that needs a picker can call it freely on every appearance. */ suspend fun prepare(): Result<Meta> = withContext(Dispatchers.IO) {- // Cheap path first. Every picker calls this on appearance, and re-reading and re-parsing- // two metadata files each time is pointless once the database is open and current.- (_status.value as? Status.Ready)?.let { return@withContext Result.success(it.meta) }+ // Cheap path, but only once the unpacked copy has been checked against the asset. Every+ // picker calls this on appearance, and re-reading two metadata files each time is pointless+ // after that.+ verified?.let { return@withContext Result.success(it) } prepareMutex.withLock {- (_status.value as? Status.Ready)?.let { return@withLock Result.success(it.meta) }+ verified?.let { return@withLock Result.success(it) } val asset = assetMeta() ?: return@withLock fail("This build has no medical catalogue")@@ -423,8 +430,9 @@ object ReferenceCatalog { installedMeta()?.let { current -> if (current == asset) { // Already unpacked from a previous run. Open it now rather than letting the- // first search pay for opening a 14 MB file.+ // first search pay for opening a 26 MB file. openHandle()+ verified = current _status.value = Status.Ready(current) return@withLock Result.success(current) }@@ -462,6 +470,7 @@ object ReferenceCatalog { metaFile.writeText(json.encodeToString(asset)) openHandle()+ verified = asset _status.value = Status.Ready(asset) Result.success(asset) } catch (e: Exception) {
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 54efcdc054..c3d1abed87 100644--- a/health/src/main/java/com/vayunmathur/health/domain/FhirRecords.kt+++ b/health/src/main/java/com/vayunmathur/health/domain/FhirRecords.kt@@ -636,6 +636,17 @@ object FhirRecords { return (root["code"] as? JsonObject).codingWithSystem(LOINC_SYSTEM)?.string("code") } + /** The resource's own `id`, needed to update rather than duplicate it on the next write. */+ fun resourceId(data: String): String? = parseObject(data)?.string("id")++ /** When an observation says it was taken, which is what orders two answers to one question. */+ fun observationEffective(data: String): Instant? {+ val root = parseObject(data) ?: return null+ return parseDateTime(root.string("effectiveDateTime"))+ ?: parseDateTime(root.string("issued"))+ ?: parseDateTime((root["effectivePeriod"] as? JsonObject).string("start"))+ }+ /** The status and estimated delivery date from a pregnancy observation. */ fun parsePregnancyStatus(data: String): Pair<PregnancyStatus, Instant?>? { val root = parseObject(data) ?: return null
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 7e83cfbf38..998559e797 100644--- a/health/src/main/java/com/vayunmathur/health/domain/SocialHistoryQuestions.kt+++ b/health/src/main/java/com/vayunmathur/health/domain/SocialHistoryQuestions.kt@@ -35,23 +35,25 @@ object SocialHistoryQuestions { val loinc: String, /** Canonical English name of the question, for `Observation.code.display`. */ val display: String,- /** Short heading for the card. */+ /**+ * The question, in full, as the instrument asks it.+ *+ * Not a topic and not a paraphrase. These are validated screening instruments whose wording+ * is the measurement: drop "within the past 12 months" or "before we got money to buy more"+ * and the answer no longer means what the code says it means. It is shown as a wrapping row+ * title rather than a field label for the same reason — there has to be room for all of it.+ */ val titleRes: Int,- /** The question as actually asked, since these only make sense in full. */- val promptRes: Int, val answers: List<Answer>, ) - /** Never / Once or twice / Monthly / Weekly / Daily — shared by the two frequency screens. */- private val FREQUENCY = listOf(- Answer("LA6270-8", "Never", R.string.freq_never),- Answer("LA26460-8", "Once or twice", R.string.freq_once_or_twice),- Answer("LA18876-5", "Monthly", R.string.freq_monthly),- Answer("LA18891-4", "Weekly", R.string.freq_weekly),- Answer("LA18934-2", "Daily or almost daily", R.string.freq_daily),- )-- /** Often / Sometimes / Never true — LOINC list LL5890-0, the Hunger Vital Sign answers. */+ /**+ * LOINC list LL5890-0, shared by both Hunger Vital Sign questions.+ *+ * "Often true" is the instrument's own answer and reads correctly because the statement it+ * agrees with is on screen above it. Rewriting these to be self-describing was an attempt to+ * compensate for having hidden the question, which was the actual mistake.+ */ private val HUNGER = listOf( Answer("LA28397-0", "Often true", R.string.hvs_often_true), Answer("LA6729-3", "Sometimes true", R.string.hvs_sometimes_true),@@ -62,7 +64,6 @@ object SocialHistoryQuestions { loinc = "68518-0", display = "How often do you have a drink containing alcohol", titleRes = R.string.social_alcohol,- promptRes = R.string.social_alcohol_prompt, // LL2179-1. Its own scale, not the shared one - AUDIT-C asks about frequency of any // drinking rather than counting occasions. answers = listOf(@@ -79,15 +80,19 @@ object SocialHistoryQuestions { display = "How many times in the past year have you used an illegal drug or used a " + "prescription medication for non-medical reasons", titleRes = R.string.social_drugs,- promptRes = R.string.social_drugs_prompt,- answers = FREQUENCY,+ answers = listOf(+ Answer("LA6270-8", "Never", R.string.freq_never),+ Answer("LA26460-8", "Once or twice", R.string.freq_once_or_twice),+ Answer("LA18876-5", "Monthly", R.string.freq_monthly),+ Answer("LA18891-4", "Weekly", R.string.freq_weekly),+ Answer("LA18934-2", "Daily or almost daily", R.string.freq_daily),+ ), ) val HOUSING = Question( loinc = "71802-3", display = "Housing status", titleRes = R.string.social_housing,- promptRes = R.string.social_housing_prompt, // LL5876-9, the three-answer PRAPARE-style list rather than the older five-answer one, // which was written for a clinician describing a patient ("Patient is homeless"). answers = listOf(@@ -102,7 +107,6 @@ object SocialHistoryQuestions { display = "Within the past 12 months we worried whether our food would run out before we " + "got money to buy more", titleRes = R.string.social_food_worried,- promptRes = R.string.social_food_worried_prompt, answers = HUNGER, ) @@ -111,7 +115,6 @@ object SocialHistoryQuestions { display = "Within the past 12 months the food we bought just didn't last and we didn't " + "have money to get more", titleRes = R.string.social_food_ran_out,- promptRes = R.string.social_food_ran_out_prompt, answers = HUNGER, ) @@ -120,7 +123,6 @@ object SocialHistoryQuestions { display = "Has lack of transportation kept you from medical appointments, meetings, work, " + "or from getting things needed for daily living", titleRes = R.string.social_transport,- promptRes = R.string.social_transport_prompt, // LL5336-4. "I choose not to answer" is kept: declining is a real answer and the record // should be able to say so rather than leaving it indistinguishable from never asked. answers = listOf(@@ -131,7 +133,13 @@ object SocialHistoryQuestions { ), ) - val ALL = listOf(ALCOHOL, DRUGS, HOUSING, FOOD_WORRIED, FOOD_RAN_OUT, TRANSPORT)+ /** Habits. Grouped only so the page reads as two short lists rather than one long one. */+ val LIFESTYLE = listOf(ALCOHOL, DRUGS)++ /** The social determinants: where you live, whether you can eat, whether you can travel. */+ val CIRCUMSTANCES = listOf(HOUSING, FOOD_WORRIED, FOOD_RAN_OUT, TRANSPORT)++ val ALL = LIFESTYLE + CIRCUMSTANCES fun byLoinc(code: String): Question? = ALL.firstOrNull { it.loinc == code } }
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 5df5c9be42..b05c692cbd 100644--- a/health/src/main/java/com/vayunmathur/health/platform/MedicalViewModel.kt+++ b/health/src/main/java/com/vayunmathur/health/platform/MedicalViewModel.kt@@ -23,10 +23,12 @@ 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.RepeatUnit import com.vayunmathur.health.data.SmokingStatus import com.vayunmathur.health.data.VaccinationEntry import com.vayunmathur.health.domain.FhirRecords+import com.vayunmathur.health.domain.SocialHistoryQuestions import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted@@ -96,6 +98,11 @@ class MedicalViewModel( .map { it ?: HealthProfile() } .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), HealthProfile()) + /** Answered social history questions, keyed by the LOINC code of the question. */+ val profileAnswers: StateFlow<Map<String, ProfileAnswer>> = repository.getProfileAnswersFlow()+ .map { all -> all.associateBy { it.loincCode } }+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyMap())+ /** Attachments keyed by the vaccination they belong to. */ val attachments: StateFlow<Map<String, List<MedicalAttachment>>> = repository.getAttachmentsFlow()@@ -776,6 +783,54 @@ class MedicalViewModel( repository.upsertProfile(profile.copy(dataSourceId = dataSourceId)) } + /** Records an answer to one social history question, dated now. */+ fun setSocialHistoryAnswer(+ question: SocialHistoryQuestions.Question,+ answer: SocialHistoryQuestions.Answer,+ ) {+ viewModelScope.launch {+ val existing = repository.getProfileAnswer(question.loinc)+ val row = ProfileAnswer(+ loincCode = question.loinc,+ answerCode = answer.code,+ recordedAt = Instant.now(),+ // Reusing the id is what makes this an update. Minting a new one leaves the old+ // observation behind, and the next import then sees two answers to one question.+ fhirResourceId = existing?.fhirResourceId ?: Uuid.random().toString(),+ dataSourceId = existing?.dataSourceId,+ )+ repository.upsertProfileAnswer(row)++ val dataSourceId = PersonalHealthRecords.dataSourceId() ?: return@launch+ val fhirId = row.fhirResourceId ?: return@launch+ PersonalHealthRecords.upsert(+ dataSourceId,+ FhirRecords.socialHistoryAnswerJson(fhirId, question, answer, row.recordedAt),+ ) ?: return@launch+ repository.upsertProfileAnswer(row.copy(dataSourceId = dataSourceId))+ }+ }++ /**+ * Un-answers a question, removing the observation as well as the local row.+ *+ * Deleting only locally would leave the answer in Health Connect for the next import to bring+ * straight back.+ */+ fun clearSocialHistoryAnswer(question: SocialHistoryQuestions.Question) {+ viewModelScope.launch {+ val existing = repository.getProfileAnswer(question.loinc)+ repository.deleteProfileAnswer(question.loinc)+ val dataSourceId = existing?.dataSourceId ?: return@launch+ val fhirId = existing.fhirResourceId ?: return@launch+ PersonalHealthRecords.delete(+ dataSourceId,+ PersonalHealthRecords.observationResourceType,+ fhirId,+ )+ }+ }+ // --- Import -------------------------------------------------------------- /**@@ -843,16 +898,67 @@ class MedicalViewModel( if (resources.isEmpty()) return var profile = repository.getProfile() ?: HealthProfile()++ // Newest answer per question. A category read returns every social-history observation the+ // phone holds, which can include several for the same question - from a provider, or from+ // an older build of this app - and picking whichever came last in the list is how an answer+ // appears to revert after being set.+ val newest = mutableMapOf<String, ProfileAnswer>()+ resources.forEach { resource ->- when (FhirRecords.observationLoincCode(resource.data)) {+ val loinc = FhirRecords.observationLoincCode(resource.data)+ when (loinc) { FhirRecords.LOINC_PREGNANCY_STATUS -> FhirRecords.parsePregnancyStatus(resource.data)?.let { (status, due) ->- profile = profile.copy(pregnancyStatus = status, dueDate = due)+ profile = profile.copy(+ pregnancyStatus = status,+ dueDate = due,+ pregnancyFhirId = profile.pregnancyFhirId+ ?: FhirRecords.resourceId(resource.data),+ ) } FhirRecords.LOINC_SMOKING_STATUS -> FhirRecords.parseSmokingStatus(resource.data)?.let { status ->- profile = profile.copy(smokingStatus = status)+ profile = profile.copy(+ smokingStatus = status,+ smokingFhirId = profile.smokingFhirId+ ?: FhirRecords.resourceId(resource.data),+ )+ }+ else -> {+ // 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@forEach+ val answerCode = FhirRecords.parseSocialHistoryAnswer(resource.data)+ ?: return@forEach+ // 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@forEach++ val candidate = ProfileAnswer(+ loincCode = question.loinc,+ 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@forEach,+ fhirResourceId = FhirRecords.resourceId(resource.data),+ dataSourceId = resource.dataSourceId,+ )+ val held = newest[question.loinc]+ if (held == null || candidate.recordedAt.isAfter(held.recordedAt)) {+ newest[question.loinc] = candidate }+ }+ }+ }++ 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+ // import was still reading, and their answer should win over what was on disk before.+ if (local == null || incoming.recordedAt.isAfter(local.recordedAt)) {+ repository.upsertProfileAnswer(incoming) } } repository.upsertProfile(profile)
health/src/main/java/com/vayunmathur/health/ui/AboutYouPage.kt
diff --git a/health/src/main/java/com/vayunmathur/health/ui/AboutYouPage.kt b/health/src/main/java/com/vayunmathur/health/ui/AboutYouPage.ktindex e731662d72..3a4f16e1c0 100644--- a/health/src/main/java/com/vayunmathur/health/ui/AboutYouPage.kt+++ b/health/src/main/java/com/vayunmathur/health/ui/AboutYouPage.kt@@ -1,29 +1,35 @@ package com.vayunmathur.health.ui import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.vayunmathur.health.R import com.vayunmathur.health.Route import com.vayunmathur.health.data.PregnancyStatus+import com.vayunmathur.health.data.ProfileAnswer import com.vayunmathur.health.data.SmokingStatus+import com.vayunmathur.health.domain.SocialHistoryQuestions import com.vayunmathur.health.platform.MedicalViewModel+import com.vayunmathur.health.ui.components.AnswerPickerDialog import com.vayunmathur.health.ui.components.MedicalStorageNotice import com.vayunmathur.health.ui.components.PickerField+import com.vayunmathur.health.ui.components.SectionLabel import com.vayunmathur.library.ui.Card import com.vayunmathur.library.ui.ExperimentalMaterial3Api-import com.vayunmathur.library.ui.FormSection import com.vayunmathur.library.ui.LazyListScaffold-import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.SettingsExposedSelectRow-import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.SettingsRow import com.vayunmathur.library.ui.appBarScrollBehavior import com.vayunmathur.library.ui.dialog.DateSelection import com.vayunmathur.library.util.NavBackStack@@ -35,20 +41,23 @@ import kotlin.time.Clock private const val DUE_DATE_KEY = "about-you/due-date" /**- * The standing facts about the user: pregnancy status and smoking status.+ * The standing facts about the user: the things Health Connect models as observations of a *current+ * state* rather than events. *- * These are the two categories Health Connect models as observations of a *current state* rather- * than events, so they are a short form of selectors rather than a log. Both are things a clinician- * checks before prescribing or screening, which is why they get their own screen and their own- * consent toggles rather than being buried in the conditions list.+ * Three grouped cards rather than a card per question. Each question is one row: the question in+ * full as the row title, the current answer beneath it, tapping opens the answers. That keeps the+ * instrument's own wording — which is the measurement, not decoration — without the heading, prompt+ * paragraph and recorded-on line that turned a short form into several screens of scrolling. *- * Each change writes a new dated observation rather than editing the previous one — see- * `MedicalViewModel.setPregnancyStatus`.+ * Every question starts at *Not answered* and can be returned to it. Defaulting to the first real+ * option would put "Never" against alcohol for someone who has never opened this screen, and the+ * record would then assert something the user never said. */ @OptIn(ExperimentalMaterial3Api::class) @Composable fun AboutYouPage(backStack: NavBackStack<Route>, viewModel: MedicalViewModel) { val profile by viewModel.profile.collectAsState()+ val answers by viewModel.profileAnswers.collectAsState() LaunchedEffect(Unit) { viewModel.importFromHealthConnect() } @@ -60,7 +69,7 @@ fun AboutYouPage(backStack: NavBackStack<Route>, viewModel: MedicalViewModel) { title = stringResource(R.string.about_you), scrollBehavior = appBarScrollBehavior(), horizontalPadding = 16.dp,- verticalArrangement = Arrangement.spacedBy(12.dp),+ verticalArrangement = Arrangement.spacedBy(8.dp), ) { if (!viewModel.healthConnectAvailable) { item { MedicalStorageNotice() }@@ -68,18 +77,15 @@ fun AboutYouPage(backStack: NavBackStack<Route>, viewModel: MedicalViewModel) { item { Card(modifier = Modifier.fillMaxWidth()) {- FormSection(- title = stringResource(R.string.section_pregnancy),- modifier = Modifier.padding(16.dp),- ) {- val labels = PregnancyStatus.entries.associateWith {+ CardRows {+ val pregnancyLabels = PregnancyStatus.entries.associateWith { stringResource(it.labelRes()) } SettingsExposedSelectRow( label = stringResource(R.string.field_pregnancy_status), selected = profile.pregnancyStatus, options = PregnancyStatus.entries,- itemLabel = { labels.getValue(it) },+ itemLabel = { pregnancyLabels.getValue(it) }, onSelect = { picked -> viewModel.setPregnancyStatus( picked,@@ -109,59 +115,93 @@ fun AboutYouPage(backStack: NavBackStack<Route>, viewModel: MedicalViewModel) { }, ) }- profile.pregnancyRecordedAt?.let {- RecordedLine(medicalDateString(it))- }- }- }- } - item {- Card(modifier = Modifier.fillMaxWidth()) {- FormSection(- title = stringResource(R.string.section_smoking),- modifier = Modifier.padding(16.dp),- ) {- val labels = SmokingStatus.entries.associateWith {+ val smokingLabels = SmokingStatus.entries.associateWith { stringResource(it.labelRes()) } SettingsExposedSelectRow( label = stringResource(R.string.field_smoking_status), selected = profile.smokingStatus, options = SmokingStatus.entries,- itemLabel = { labels.getValue(it) },+ itemLabel = { smokingLabels.getValue(it) }, onSelect = { picked -> viewModel.setSmokingStatus(picked) }, )- profile.smokingRecordedAt?.let {- RecordedLine(medicalDateString(it))- } } } }++ item { SectionLabel(stringResource(R.string.section_lifestyle)) }+ item { QuestionCard(SocialHistoryQuestions.LIFESTYLE, answers, viewModel) }++ item { SectionLabel(stringResource(R.string.section_circumstances)) }+ item { QuestionCard(SocialHistoryQuestions.CIRCUMSTANCES, answers, viewModel) } } } -/** When the answer above was last given. These are dated observations, not settings. */+/** A group of questions as one card of rows, each opening a dialog to answer it. */ @Composable-private fun RecordedLine(date: String) {- Text(- stringResource(R.string.recorded_on, date),- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.onSurfaceVariant,- )+private fun QuestionCard(+ questions: List<SocialHistoryQuestions.Question>,+ answers: Map<String, ProfileAnswer>,+ viewModel: MedicalViewModel,+) {+ var asking by remember { mutableStateOf<SocialHistoryQuestions.Question?>(null) }++ asking?.let { question ->+ AnswerPickerDialog(+ question = question,+ selected = question.answers+ .firstOrNull { it.code == answers[question.loinc]?.answerCode },+ onPick = { picked ->+ if (picked == null) {+ viewModel.clearSocialHistoryAnswer(question)+ } else {+ viewModel.setSocialHistoryAnswer(question, picked)+ }+ asking = null+ },+ onDismiss = { asking = null },+ )+ }++ Card(modifier = Modifier.fillMaxWidth()) {+ Column {+ questions.forEach { question ->+ val selected = question.answers+ .firstOrNull { it.code == answers[question.loinc]?.answerCode }+ SettingsRow(+ // The question goes in the title, which wraps, rather than in a field label,+ // which would truncate it.+ title = stringResource(question.titleRes),+ supportingText = selected?.let { stringResource(it.labelRes) }+ ?: stringResource(R.string.not_answered),+ onClick = { asking = question },+ )+ }+ }+ }+}++/** The padding and spacing shared by both cards, so they line up with each other. */+@Composable+private fun CardRows(content: @Composable () -> Unit) {+ Column(+ modifier = Modifier.padding(16.dp),+ verticalArrangement = Arrangement.spacedBy(12.dp),+ ) { content() } } private fun today() = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()).date internal fun PregnancyStatus.labelRes() = when (this) {- PregnancyStatus.Unknown -> R.string.pregnancy_unknown+ PregnancyStatus.Unknown -> R.string.not_answered PregnancyStatus.Pregnant -> R.string.pregnancy_pregnant PregnancyStatus.NotPregnant -> R.string.pregnancy_not_pregnant } internal fun SmokingStatus.labelRes() = when (this) {- SmokingStatus.Unknown -> R.string.smoking_unknown+ SmokingStatus.Unknown -> R.string.not_answered SmokingStatus.Never -> R.string.smoking_never SmokingStatus.Former -> R.string.smoking_former SmokingStatus.Current -> R.string.smoking_current
health/src/main/java/com/vayunmathur/health/ui/MedicationPage.kt
diff --git a/health/src/main/java/com/vayunmathur/health/ui/MedicationPage.kt b/health/src/main/java/com/vayunmathur/health/ui/MedicationPage.ktindex d6800dbf7e..6c38c8775b 100644--- a/health/src/main/java/com/vayunmathur/health/ui/MedicationPage.kt+++ b/health/src/main/java/com/vayunmathur/health/ui/MedicationPage.kt@@ -22,6 +22,7 @@ import com.vayunmathur.health.data.MedicationStatus import com.vayunmathur.health.domain.DoseSchedule import com.vayunmathur.health.platform.MedicalViewModel import com.vayunmathur.health.ui.components.MedicalStorageNotice+import com.vayunmathur.health.ui.components.SectionLabel import com.vayunmathur.library.ui.Card import com.vayunmathur.library.ui.ConfirmDialog import com.vayunmathur.library.ui.DateString@@ -130,16 +131,6 @@ fun MedicationPage(backStack: NavBackStack<Route>, viewModel: MedicalViewModel) } } -@Composable-private fun SectionLabel(text: String) {- Text(- text,- style = MaterialTheme.typography.titleSmall,- color = MaterialTheme.colorScheme.primary,- modifier = Modifier.padding(top = 8.dp),- )-}- @Composable private fun MedicationCard( entry: MedicationEntry,
health/src/main/java/com/vayunmathur/health/ui/VaccinationsPage.kt
diff --git a/health/src/main/java/com/vayunmathur/health/ui/VaccinationsPage.kt b/health/src/main/java/com/vayunmathur/health/ui/VaccinationsPage.ktindex 5635203d54..ec30bad1b1 100644--- a/health/src/main/java/com/vayunmathur/health/ui/VaccinationsPage.kt+++ b/health/src/main/java/com/vayunmathur/health/ui/VaccinationsPage.kt@@ -34,8 +34,6 @@ import com.vayunmathur.library.ui.ExperimentalMaterial3Api import com.vayunmathur.library.ui.ExternalIntents import com.vayunmathur.library.ui.FloatingActionButton import com.vayunmathur.library.ui.IconAdd-import com.vayunmathur.library.ui.IconButton-import com.vayunmathur.library.ui.IconRefresh import com.vayunmathur.library.ui.IconVaccine import com.vayunmathur.library.ui.LazyListScaffold import com.vayunmathur.library.ui.ListItem@@ -81,11 +79,6 @@ fun VaccinationsPage(backStack: NavBackStack<Route>, viewModel: MedicalViewModel scrollBehavior = appBarScrollBehavior(), horizontalPadding = 16.dp, verticalArrangement = Arrangement.spacedBy(8.dp),- actions = {- if (viewModel.healthConnectAvailable) {- IconButton(onClick = { viewModel.importFromHealthConnect() }) { IconRefresh() }- }- }, floatingActionButton = { FloatingActionButton( onClick = {
health/src/main/java/com/vayunmathur/health/ui/components/AnswerPickerDialog.kt
diff --git a/health/src/main/java/com/vayunmathur/health/ui/components/AnswerPickerDialog.kt b/health/src/main/java/com/vayunmathur/health/ui/components/AnswerPickerDialog.ktnew file mode 100644index 0000000000..20c7c52295--- /dev/null+++ b/health/src/main/java/com/vayunmathur/health/ui/components/AnswerPickerDialog.kt@@ -0,0 +1,84 @@+package com.vayunmathur.health.ui.components++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.selection.selectable+import androidx.compose.foundation.verticalScroll+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import com.vayunmathur.health.R+import com.vayunmathur.health.domain.SocialHistoryQuestions+import com.vayunmathur.library.ui.AlertDialog+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.R as UiR+import com.vayunmathur.library.ui.RadioButton+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton++/**+ * Picks one answer to a social history question.+ *+ * A dialog rather than a dropdown because both halves need room: the question is a full sentence+ * from a screening instrument, and several of the answers are sentences too. A dropdown anchored to+ * a field label would truncate both.+ *+ * Choosing dismisses immediately — there is no confirm button, because a single tap on a radio row+ * is unambiguous and a second tap to agree with yourself is just friction.+ */+@Composable+internal fun AnswerPickerDialog(+ question: SocialHistoryQuestions.Question,+ selected: SocialHistoryQuestions.Answer?,+ onPick: (SocialHistoryQuestions.Answer?) -> Unit,+ onDismiss: () -> Unit,+) {+ AlertDialog(+ onDismissRequest = onDismiss,+ title = { Text(stringResource(question.titleRes)) },+ text = {+ Column(+ modifier = Modifier.verticalScroll(rememberScrollState()),+ verticalArrangement = Arrangement.spacedBy(4.dp),+ ) {+ // Leaving a question unanswered has to stay reachable, not just be the state you+ // start in — otherwise a mistap is permanent.+ AnswerRow(+ label = stringResource(R.string.not_answered),+ selected = selected == null,+ onClick = { onPick(null) },+ )+ question.answers.forEach { answer ->+ AnswerRow(+ label = stringResource(answer.labelRes),+ selected = answer == selected,+ onClick = { onPick(answer) },+ )+ }+ }+ },+ confirmButton = {+ TextButton(onClick = onDismiss) { Text(stringResource(UiR.string.cancel)) }+ },+ )+}++@Composable+private fun AnswerRow(label: String, selected: Boolean, onClick: () -> Unit) {+ Row(+ modifier = Modifier+ .fillMaxWidth()+ // selectable on the row, so the whole line is the target rather than the radio alone.+ .selectable(selected = selected, onClick = onClick, role = null),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ RadioButton(selected = selected, onClick = onClick)+ Text(label, style = MaterialTheme.typography.bodyLarge)+ }+}
health/src/main/java/com/vayunmathur/health/ui/components/SectionLabel.kt
diff --git a/health/src/main/java/com/vayunmathur/health/ui/components/SectionLabel.kt b/health/src/main/java/com/vayunmathur/health/ui/components/SectionLabel.ktnew file mode 100644index 0000000000..a91f3f5196--- /dev/null+++ b/health/src/main/java/com/vayunmathur/health/ui/components/SectionLabel.kt@@ -0,0 +1,19 @@+package com.vayunmathur.health.ui.components++import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text++/** A heading between groups of cards in the medical logs. */+@Composable+internal fun SectionLabel(text: String) {+ Text(+ text,+ style = MaterialTheme.typography.titleSmall,+ color = MaterialTheme.colorScheme.primary,+ modifier = Modifier.padding(top = 8.dp),+ )+}
health/src/main/res/values-sv/strings.xml
diff --git a/health/src/main/res/values-sv/strings.xml b/health/src/main/res/values-sv/strings.xmlindex 884dd05cd5..5c002db413 100644--- a/health/src/main/res/values-sv/strings.xml+++ b/health/src/main/res/values-sv/strings.xml@@ -99,14 +99,11 @@ <string name="log_meal">Logga måltid</string> <string name="log_body_metric">Logga <xliff:g id="metric" example="Weight">%1$s</xliff:g></string> <string name="nav_today">I dag</string>- <string name="nav_activity">Aktivitet</string> <string name="nav_nutrition">Näring</string> <string name="nav_body">Kropp</string> <string name="section_latest_vitals">Senaste vitalvärdena</string> <string name="section_last_night">I natt</string> <string name="section_quick_stats">Snabbstatistik</string>- <string name="section_today_activity">I dag</string>- <string name="section_this_week">Den här veckan</string> <string name="label_exercise">Träning</string> <string name="no_workouts">Inga träningspass har registrerats</string> <string name="view_full_breakdown">Visa fullständig fördelning</string>
health/src/main/res/values/strings.xml
diff --git a/health/src/main/res/values/strings.xml b/health/src/main/res/values/strings.xmlindex a103955df8..0802e74218 100644--- a/health/src/main/res/values/strings.xml+++ b/health/src/main/res/values/strings.xml@@ -580,30 +580,78 @@ <string name="about_you">About you</string> <!-- RecordsPage: Overline on the About you row, distinguishing it from the logs. Noun phrase --> <string name="about_you_overline">Current status</string>- <!-- AboutYouPage: Form section heading. Noun -->- <string name="section_pregnancy">Pregnancy</string>- <!-- AboutYouPage: Form section heading. Noun -->- <string name="section_smoking">Smoking</string> <!-- AboutYouPage: Selector label for pregnancy status. Noun phrase --> <string name="field_pregnancy_status">Status</string> <!-- AboutYouPage: Estimated delivery date. Noun phrase --> <string name="field_due_date">Due date</string> <!-- AboutYouPage: Selector label for smoking status. Noun phrase --> <string name="field_smoking_status">Status</string>- <!-- AboutYouPage: When the answer above was last given, %1$s is a date -->- <string name="recorded_on">Recorded <xliff:g example="4 March 2026" id="date">%1$s</xliff:g></string>- <!-- Pregnancy status: never answered. Adjective -->- <string name="pregnancy_unknown">Not answered</string> <!-- Pregnancy status: currently pregnant. Adjective --> <string name="pregnancy_pregnant">Pregnant</string> <!-- Pregnancy status: not currently pregnant. Adjective phrase --> <string name="pregnancy_not_pregnant">Not pregnant</string>- <!-- Smoking status: never answered. Adjective -->- <string name="smoking_unknown">Not answered</string> <!-- Smoking status: has never smoked. Adverb --> <string name="smoking_never">Never smoked</string> <!-- Smoking status: used to smoke. Adjective --> <string name="smoking_former">Former smoker</string> <!-- Smoking status: currently smokes. Verb phrase --> <string name="smoking_current">Currently smokes</string>++ <!-- AboutYouPage: The alcohol question, worded as AUDIT-C asks it. Question -->+ <string name="social_alcohol">How often do you have a drink containing alcohol?</string>+ <!-- AboutYouPage: The drug use question, worded as the NIDA quick screen asks it. Question -->+ <string name="social_drugs">How many times in the past year have you used an illegal drug, or a prescription medication for non-medical reasons?</string>+ <!-- AboutYouPage: The housing question. Question -->+ <string name="social_housing">What is your housing situation today?</string>+ <!-- AboutYouPage: First Hunger Vital Sign statement, to be agreed with -->+ <string name="social_food_worried">Within the past 12 months, we worried whether our food would run out before we got money to buy more.</string>+ <!-- AboutYouPage: Second Hunger Vital Sign statement, to be agreed with -->+ <string name="social_food_ran_out">Within the past 12 months, the food we bought just did not last and we did not have money to get more.</string>+ <!-- AboutYouPage: The transport question. Question -->+ <string name="social_transport">Has a lack of transport kept you from medical appointments, work, or from getting things you need for daily living?</string>+ <!-- AboutYouPage: Section heading over the habit questions. Noun -->+ <string name="section_lifestyle">Lifestyle</string>+ <!-- AboutYouPage: Section heading over the housing, food and transport questions. Noun -->+ <string name="section_circumstances">Circumstances</string>+ <!-- AboutYouPage: Default option on every question the user has not answered. Adjective -->+ <string name="not_answered">Not answered</string>++ <!-- Answer to the drug use question: not at all. Adverb -->+ <string name="freq_never">Never</string>+ <!-- Answer to the drug use question: once or twice in the year. Adverb phrase -->+ <string name="freq_once_or_twice">Once or twice</string>+ <!-- Answer to the drug use question: about monthly. Adverb -->+ <string name="freq_monthly">Monthly</string>+ <!-- Answer to the drug use question: about weekly. Adverb -->+ <string name="freq_weekly">Weekly</string>+ <!-- Answer to the drug use question: every day or nearly. Adverb phrase -->+ <string name="freq_daily">Daily or almost daily</string>+ <!-- Alcohol frequency answer: monthly at most. Adverb phrase -->+ <string name="audit_monthly_or_less">Monthly or less</string>+ <!-- Alcohol frequency answer. Adverb phrase -->+ <string name="audit_2_4_month">2 to 4 times a month</string>+ <!-- Alcohol frequency answer. Adverb phrase -->+ <string name="audit_2_3_week">2 to 3 times a week</string>+ <!-- Alcohol frequency answer. Adverb phrase -->+ <string name="audit_4_plus_week">4 or more times a week</string>+ <!-- Housing answer: stable housing. Sentence -->+ <string name="housing_steady">I have a steady place to live</string>+ <!-- Housing answer: housed but at risk. Sentence -->+ <string name="housing_worried">I have a place today, but worry about losing it</string>+ <!-- Housing answer: unstably housed. Sentence -->+ <string name="housing_none">I do not have a steady place to live</string>+ <!-- Hunger Vital Sign answer: the statement was often true. Adjective phrase -->+ <string name="hvs_often_true">Often true</string>+ <!-- Hunger Vital Sign answer: the statement was sometimes true. Adjective phrase -->+ <string name="hvs_sometimes_true">Sometimes true</string>+ <!-- Hunger Vital Sign answer: the statement was never true. Adjective phrase -->+ <string name="hvs_never_true">Never true</string>+ <!-- Transport answer: has prevented medical care. Sentence -->+ <string name="transport_medical">Yes, from medical appointments or getting medication</string>+ <!-- Transport answer: has prevented other essentials. Sentence -->+ <string name="transport_non_medical">Yes, from work or other things I need</string>+ <!-- Transport answer: transport is not a problem. Adverb -->+ <string name="transport_no">No</string>+ <!-- Answer available on some questions when the user would rather not say. Sentence -->+ <string name="decline_to_answer">I choose not to answer</string> </resources>
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.ktnew file mode 100644index 0000000000..2ab9c4920b--- /dev/null+++ b/health/src/test/java/com/vayunmathur/health/domain/SocialHistoryQuestionsTest.kt@@ -0,0 +1,194 @@+package com.vayunmathur.health.domain++import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.jsonArray+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive+import org.junit.Test+import java.time.Instant+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Guards the social history question table.+ *+ * These codes were read out of the LOINC 2.83 release rather than recalled, and the point of this+ * suite is that they stay that way — a wrong concept id in a medical record is not a cosmetic bug,+ * and nothing else in the build would notice one.+ */+class SocialHistoryQuestionsTest {++ private fun parse(json: String) = Json.parseToJsonElement(json).jsonObject++ private fun JsonObject.str(key: String) = this[key]?.jsonPrimitive?.content++ @Test+ fun `every question has a well formed LOINC code and at least two answers`() {+ val loincPattern = Regex("""^\d{3,6}-\d$""")+ for (question in SocialHistoryQuestions.ALL) {+ assertTrue(+ loincPattern.matches(question.loinc),+ "${question.loinc} is not shaped like a LOINC code",+ )+ assertTrue(+ question.answers.size >= 2,+ "${question.loinc} needs answers to be worth asking",+ )+ assertTrue(question.display.isNotBlank(), "${question.loinc} has no display name")+ }+ }++ @Test+ fun `every answer has a well formed LA code`() {+ val laPattern = Regex("""^LA\d+-\d$""")+ for (question in SocialHistoryQuestions.ALL) {+ for (answer in question.answers) {+ assertTrue(+ laPattern.matches(answer.code),+ "${answer.code} on ${question.loinc} is not shaped like a LOINC answer code",+ )+ assertTrue(answer.display.isNotBlank(), "${answer.code} has no display text")+ }+ }+ }++ @Test+ fun `answer codes are unique within a question`() {+ for (question in SocialHistoryQuestions.ALL) {+ val codes = question.answers.map { it.code }+ assertEquals(+ codes.size,+ codes.distinct().size,+ "${question.loinc} repeats an answer code",+ )+ }+ }++ @Test+ fun `questions are unique and findable by their code`() {+ val codes = SocialHistoryQuestions.ALL.map { it.loinc }+ assertEquals(codes.size, codes.distinct().size, "a question code is repeated")+ for (question in SocialHistoryQuestions.ALL) {+ assertEquals(question, SocialHistoryQuestions.byLoinc(question.loinc))+ }+ assertNull(SocialHistoryQuestions.byLoinc("00000-0"))+ }++ @Test+ fun `smoking and pregnancy are not in the table`() {+ // Both have their own US Core profiles bound to SNOMED rather than to a LOINC answer list,+ // so they are handled as their own fields. Adding them here would write them twice.+ assertNull(SocialHistoryQuestions.byLoinc(FhirRecords.LOINC_SMOKING_STATUS))+ assertNull(SocialHistoryQuestions.byLoinc(FhirRecords.LOINC_PREGNANCY_STATUS))+ }++ @Test+ fun `every answer round trips through its observation`() {+ val recordedAt = Instant.parse("2026-05-02T10:00:00Z")+ for (question in SocialHistoryQuestions.ALL) {+ for (answer in question.answers) {+ val json = FhirRecords.socialHistoryAnswerJson("obs", question, answer, recordedAt)++ assertEquals(+ question.loinc,+ FhirRecords.observationLoincCode(json),+ "question code lost for ${question.loinc}",+ )+ assertEquals(+ answer.code,+ FhirRecords.parseSocialHistoryAnswer(json),+ "answer code lost for ${answer.code}",+ )+ }+ }+ }++ @Test+ fun `the observation is categorised as social history and coded in LOINC`() {+ val question = SocialHistoryQuestions.ALCOHOL+ val root = parse(+ FhirRecords.socialHistoryAnswerJson(+ "obs", question, question.answers.first(), Instant.EPOCH+ )+ )++ assertEquals("Observation", root.str("resourceType"))+ assertEquals("final", root.str("status"))+ assertEquals(+ "social-history",+ root["category"]!!.jsonArray.single().jsonObject["coding"]!!+ .jsonArray.single().jsonObject.str("code"),+ )+ val code = root["code"]!!.jsonObject["coding"]!!.jsonArray.single().jsonObject+ assertEquals(FhirRecords.LOINC_SYSTEM, code.str("system"))+ assertEquals("68518-0", code.str("code"))++ // Both question and answer are LOINC, so no second terminology is involved.+ val value = root["valueCodeableConcept"]!!.jsonObject["coding"]!!+ .jsonArray.single().jsonObject+ assertEquals(FhirRecords.LOINC_SYSTEM, value.str("system"))+ }++ @Test+ fun `the two hunger vital sign questions share one answer list`() {+ // Same LOINC list, and now the same labels too: "Often true" reads correctly because the+ // statement it agrees with is the row title, in full, rather than a paraphrase of it.+ assertEquals(+ SocialHistoryQuestions.FOOD_WORRIED.answers,+ SocialHistoryQuestions.FOOD_RAN_OUT.answers,+ )+ }++ @Test+ fun `the label shown is separate from the wording written to the record`() {+ val question = SocialHistoryQuestions.FOOD_WORRIED+ val often = question.answers.first()++ // labelRes is ours and translatable; code and display belong to LOINC and are what travels+ // to Health Connect, so rewording a button can never change what the record says.+ assertEquals("LA28397-0", often.code)+ assertEquals("Often true", often.display)++ val json = FhirRecords.socialHistoryAnswerJson("obs", question, often, Instant.EPOCH)+ val value = parse(json)["valueCodeableConcept"]!!.jsonObject+ assertEquals(+ "Often true",+ value["coding"]!!.jsonArray.single().jsonObject.str("display"),+ )+ assertEquals("LA28397-0", FhirRecords.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"))+ }++ @Test+ fun `an observation with no coded value yields no answer`() {+ val bare = """+ {+ "resourceType": "Observation",+ "id": "x",+ "code": { "coding": [ { "system": "http://loinc.org", "code": "68518-0" } ] }+ }+ """.trimIndent()++ assertEquals("68518-0", FhirRecords.observationLoincCode(bare))+ assertNull(FhirRecords.parseSocialHistoryAnswer(bare))+ }++ @Test+ fun `the alcohol question uses the AUDIT-C scale rather than the shared one`() {+ // AUDIT-C asks how often you drink at all; the shared scale counts occasions of use. They+ // read similarly and are different LOINC answer lists.+ val alcohol = SocialHistoryQuestions.ALCOHOL.answers.map { it.code }+ val drugs = SocialHistoryQuestions.DRUGS.answers.map { it.code }++ assertNotNull(alcohol.firstOrNull { it == "LA18926-8" })+ assertTrue(alcohol != drugs)+ }+}