health: split the medication plan from the doses taken
- Commit
8db33b4304a8c3add7fd67b8ea2de49d26938cf1- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-12 02:43 UTC (2 months ago)
- Parents
e297fa9
MedicationRequest is the plan to take something and carries the dosage
instructions; MedicationStatement is a report that a dose was taken. The
app had the whole regimen as a statement, which asserts the entire course
had already been consumed.
So a medication is now a MedicationRequest with intent=plan and
reportedBoolean=true - a plan the user is reporting, not a prescription
somebody wrote - and a taken dose is a completed MedicationStatement with
a single effectiveDateTime and basedOn pointing at the request it
fulfils.
MedicationAdministration would be the exact resource for the act of
taking a tablet, but Health Connect does not accept that type.
Two things fall out of the split. Nothing needs an extension to tell a
dose from a medication any more, since they are different resource types.
And the reminder schedule finally reaches the record as
dosageInstruction.timing.repeat: times of day become timeOfDay, the
interval becomes period and periodUnit, chosen weekdays become dayOfWeek,
the end date becomes boundsPeriod. Until now it was private to this app.
An imported schedule arrives disabled - someone else's record should not
start this phone ringing.
Taken on a reminder now records a dose instead of only silencing the
alarm, and each active medication has a tick to log one without a
reminder. The row shows when it was last taken. A reminder that rang and
was ignored writes nothing: the app cannot tell whether the dose was
taken anyway, and inferring "missed" would put a clinical claim in the
record that nobody made.
Existing records are left alone. Medications written by the previous
build are bare statements with no basedOn, so they parse as neither a
medication nor a dose and are skipped rather than misread; each
re-mirrors as a request next time it is saved.
Test Plan:
72 unit tests pass, 41 of them in FhirRecordsTest, including round trips
for the request, the schedule inside it, and the dose - plus a test that
the two never parse as each other and that a bare statement is not
mistaken for a dose:
gradlew :health:testDevUnitTest
DoseScheduleTest: tests=19 failures=0
FhirRecordsTest: tests=41 failures=0
SocialHistoryQuestionsTest: tests=12 failures=0
Lint clean for health. Installed on a Pixel 9 Pro XL.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 cfd0325b43..69edf1330a 100644--- a/health/src/main/java/com/vayunmathur/health/data/HealthRepository.kt+++ b/health/src/main/java/com/vayunmathur/health/data/HealthRepository.kt@@ -126,6 +126,16 @@ class HealthRepository private constructor(context: Context) : medicalDao.getProfileAnswer(loincCode) suspend fun deleteProfileAnswer(loincCode: String) = medicalDao.deleteProfileAnswer(loincCode) + // Doses taken+ suspend fun upsertDoseEvent(event: DoseEvent) = medicalDao.upsertDoseEvent(event)+ suspend fun upsertDoseEvents(events: List<DoseEvent>) = medicalDao.upsertDoseEvents(events)+ suspend fun deleteDoseEvent(event: DoseEvent) = medicalDao.deleteDoseEvent(event)+ fun getDoseEventsFlow(): Flow<List<DoseEvent>> = medicalDao.getDoseEventsFlow()+ suspend fun getRecentDoses(medicationId: String, limit: Int): List<DoseEvent> =+ medicalDao.getRecentDoses(medicationId, limit)+ suspend fun getDoseEvent(id: String): DoseEvent? = medicalDao.getDoseEvent(id)+ suspend fun deleteDosesFor(medicationId: String) = medicalDao.deleteDosesFor(medicationId)+ /** 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 38db53012e..aae0a412d9 100644--- a/health/src/main/java/com/vayunmathur/health/data/MedicalRecords.kt+++ b/health/src/main/java/com/vayunmathur/health/data/MedicalRecords.kt@@ -108,6 +108,22 @@ data class AllergyEntry( val dataSourceId: String? = null, ) +/**+ * One dose actually taken, mirrored to Health Connect as a completed FHIR `MedicationStatement`.+ *+ * Only doses the user acknowledged are recorded. A reminder that rang and was ignored writes+ * nothing, because the app has no idea whether the dose was taken anyway — inferring "missed" from+ * an untapped notification would put a clinical claim in the record that nobody made.+ */+@Entity(indices = [Index(value = ["medicationId", "takenAt"])])+data class DoseEvent(+ @PrimaryKey val id: String,+ val medicationId: String,+ val takenAt: Instant,+ val fhirResourceId: String? = null,+ val dataSourceId: String? = null,+)+ /** Where a condition stands now. FHIR `Condition.clinicalStatus`. */ enum class ConditionStatus { Active, Recurrence, Remission, Resolved } @@ -353,4 +369,27 @@ interface MedicalDao { @Query("DELETE FROM ProfileAnswer WHERE loincCode = :loincCode") suspend fun deleteProfileAnswer(loincCode: String)++ // --- Dose events -------------------------------------------------------++ @Insert(onConflict = OnConflictStrategy.REPLACE)+ suspend fun upsertDoseEvent(event: DoseEvent)++ @Insert(onConflict = OnConflictStrategy.REPLACE)+ suspend fun upsertDoseEvents(events: List<DoseEvent>)++ @Delete+ suspend fun deleteDoseEvent(event: DoseEvent)++ @Query("SELECT * FROM DoseEvent ORDER BY takenAt DESC")+ fun getDoseEventsFlow(): Flow<List<DoseEvent>>++ @Query("SELECT * FROM DoseEvent WHERE medicationId = :medicationId ORDER BY takenAt DESC LIMIT :limit")+ suspend fun getRecentDoses(medicationId: String, limit: Int): List<DoseEvent>++ @Query("SELECT * FROM DoseEvent WHERE id = :id")+ suspend fun getDoseEvent(id: String): DoseEvent?++ @Query("DELETE FROM DoseEvent WHERE medicationId = :medicationId")+ suspend fun deleteDosesFor(medicationId: String) }
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 6f489d2e40..ab4cf8db77 100644--- a/health/src/main/java/com/vayunmathur/health/data/Record.kt+++ b/health/src/main/java/com/vayunmathur/health/data/Record.kt@@ -351,9 +351,9 @@ interface HealthDao { Record::class, Ingredient::class, Recipe::class, ServingUnit::class, RecipeIngredient::class, VaccinationEntry::class, MedicationEntry::class, MedicalAttachment::class, MedicationSchedule::class, AllergyEntry::class, ConditionEntry::class,- LabResultEntry::class, HealthProfile::class, ProfileAnswer::class,+ LabResultEntry::class, HealthProfile::class, ProfileAnswer::class, DoseEvent::class, ],- version = 10,+ version = 11, exportSchema = false ) @ColumnTypeConverters(Converters::class)@@ -531,6 +531,23 @@ abstract class HealthDatabase : RoomDatabase() { ) """.trimIndent() )+ },+ Migration(10, 11) {+ it.execSQL(+ """+ CREATE TABLE IF NOT EXISTS DoseEvent (+ id TEXT NOT NULL PRIMARY KEY,+ medicationId TEXT NOT NULL,+ takenAt INTEGER NOT NULL,+ fhirResourceId TEXT,+ dataSourceId TEXT+ )+ """.trimIndent()+ )+ it.execSQL(+ "CREATE INDEX IF NOT EXISTS index_DoseEvent_medicationId_takenAt " ++ "ON DoseEvent (medicationId, takenAt)"+ ) } ) }
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 c3d1abed87..b192d7fdbe 100644--- a/health/src/main/java/com/vayunmathur/health/domain/FhirRecords.kt+++ b/health/src/main/java/com/vayunmathur/health/domain/FhirRecords.kt@@ -5,11 +5,14 @@ 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.MedicationEntry+import com.vayunmathur.health.data.MedicationSchedule+import com.vayunmathur.health.data.MedicationStatus import com.vayunmathur.health.data.PregnancyStatus+import com.vayunmathur.health.data.RepeatUnit import com.vayunmathur.health.data.SmokingStatus-import com.vayunmathur.health.data.MedicationStatus import com.vayunmathur.health.data.VaccinationEntry import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonArray@@ -18,14 +21,17 @@ import kotlinx.serialization.json.JsonObjectBuilder import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.doubleOrNull+import kotlinx.serialization.json.intOrNull import kotlinx.serialization.json.jsonPrimitive import kotlinx.serialization.json.put import kotlinx.serialization.json.putJsonArray import kotlinx.serialization.json.putJsonObject import java.time.Instant import java.time.LocalDate+import java.time.ZoneId import java.time.ZoneOffset import java.time.format.DateTimeFormatter+import kotlinx.datetime.LocalDate as KotlinLocalDate /** * Builds and reads the FHIR R4 JSON that Health Connect's Personal Health Record store accepts.@@ -158,10 +164,29 @@ object FhirRecords { } }.toString() - fun medicationStatementJson(entry: MedicationEntry): String = buildJsonObject {- put("resourceType", "MedicationStatement")+ /**+ * A medication the user is on, as a FHIR `MedicationRequest` with `intent: plan`.+ *+ * A request rather than a statement because that is the split FHIR draws: `MedicationRequest`+ * is the plan to take something, carrying the dosage instructions; `MedicationStatement` is a+ * report that a dose was actually taken. Recording an ongoing regimen as a statement would+ * assert that the whole course had been consumed.+ *+ * `intent` is `plan` rather than `order` because nobody prescribed this — it is the user's own+ * account of what they intend to take. When a [schedule] is given it becomes+ * `dosageInstruction.timing.repeat`, which is what makes the reminder times part of the record+ * rather than a detail this app keeps to itself.+ */+ fun medicationRequestJson(+ entry: MedicationEntry,+ schedule: MedicationSchedule? = null,+ ): String = buildJsonObject {+ put("resourceType", "MedicationRequest") put("id", entry.id)- put("status", statusToFhir(entry.status))+ put("status", requestStatusToFhir(entry.status))+ put("intent", "plan")+ // The user is the source. Without this a reader would assume a clinician entered it.+ put("reportedBoolean", true) putJsonObject("medicationCodeableConcept") { if (entry.rxcui != null) { putJsonArray("coding") {@@ -177,18 +202,83 @@ object FhirRecords { put("text", fullMedicationName(entry)) } putJsonObject("subject") { put("reference", "Patient/$PATIENT_RESOURCE_ID") }- putJsonObject("effectivePeriod") {- put("start", formatDateTime(entry.startedAt))- entry.endedAt?.let { put("end", formatDateTime(it)) }- }- entry.dosageText?.takeIf { it.isNotBlank() }?.let {- putJsonArray("dosage") { add(buildJsonObject { put("text", it) }) }+ put("authoredOn", formatDateTime(entry.startedAt))++ val dosageText = entry.dosageText?.takeIf { it.isNotBlank() }+ if (dosageText != null || schedule != null) {+ putJsonArray("dosageInstruction") {+ add(+ buildJsonObject {+ dosageText?.let { put("text", it) }+ schedule?.let { putJsonObject("timing") { putRepeat(it, entry) } }+ }+ )+ } } entry.note?.takeIf { it.isNotBlank() }?.let { putJsonArray("note") { add(buildJsonObject { put("text", it) }) } } }.toString() + /**+ * The dose schedule as a FHIR `Timing.repeat`.+ *+ * The app's own model maps onto this almost exactly: times of day become `timeOfDay`, the+ * interval and its unit become `period` and `periodUnit`, chosen weekdays become `dayOfWeek`,+ * and the start and end dates become `boundsPeriod`.+ */+ private fun JsonObjectBuilder.putRepeat(+ schedule: MedicationSchedule,+ entry: MedicationEntry,+ ) {+ putJsonObject("repeat") {+ putJsonObject("boundsPeriod") {+ put("start", formatDateTime(entry.startedAt))+ val end = schedule.endDate?.let { formatScheduleDate(it) }+ ?: entry.endedAt?.let { formatDateTime(it) }+ end?.let { put("end", it) }+ }+ if (schedule.times.isNotEmpty()) {+ putJsonArray("timeOfDay") {+ schedule.times.sorted().forEach { add(JsonPrimitive(formatTimeOfDay(it))) }+ }+ // frequency is the number of times per period, which for a list of clock times is+ // simply how many there are.+ put("frequency", schedule.times.size)+ }+ put("period", schedule.interval)+ put("periodUnit", if (schedule.repeatUnit == RepeatUnit.Weekly) "wk" else "d")+ if (schedule.repeatUnit == RepeatUnit.Weekly && schedule.daysOfWeek != 0) {+ putJsonArray("dayOfWeek") {+ FHIR_DAYS.forEachIndexed { index, day ->+ if (schedule.daysOfWeek and (1 shl index) != 0) add(JsonPrimitive(day))+ }+ }+ }+ }+ }++ /** Bit 0 is Sunday, matching `MedicationSchedule.daysOfWeek`. */+ private val FHIR_DAYS = listOf("sun", "mon", "tue", "wed", "thu", "fri", "sat")++ /** A schedule date as a FHIR `date`. */+ private fun formatScheduleDate(date: KotlinLocalDate): String =+ "%04d-%02d-%02d".format(date.year, date.monthNumber, date.dayOfMonth)++ /**+ * The local calendar date of an instant, for the schedule's anchor.+ *+ * Local rather than UTC because a schedule anchored "today" means the user's today.+ */+ private fun Instant.toScheduleDate(): KotlinLocalDate {+ val local = atZone(ZoneId.systemDefault()).toLocalDate()+ return KotlinLocalDate(local.year, local.monthValue, local.dayOfMonth)+ }++ /** "08:00:00" from seconds since midnight, the form `Timing.repeat.timeOfDay` takes. */+ private fun formatTimeOfDay(seconds: Int): String =+ "%02d:%02d:%02d".format(seconds / 3600, (seconds % 3600) / 60, seconds % 60)+ /** "Amoxicillin", "500 mg", "Capsule" rendered as one line for `display` and `text`. */ fun fullMedicationName(entry: MedicationEntry): String = listOfNotNull(@@ -345,11 +435,19 @@ object FhirRecords { ) } - fun parseMedicationStatement(data: String, dataSourceId: String): MedicationEntry? {+ /**+ * A medication regimen read back from a `MedicationRequest`.+ *+ * Returns the entry and, when the request carries a `timing.repeat`, the schedule behind it —+ * a provider's instructions are worth keeping rather than flattening to a date range.+ */+ fun parseMedicationRequest(+ data: String,+ dataSourceId: String,+ ): Pair<MedicationEntry, MedicationSchedule?>? { val root = parseObject(data) ?: return null- if (root.string("resourceType") != "MedicationStatement") return null+ if (root.string("resourceType") != "MedicationRequest") return null val id = root.string("id") ?: return null- val concept = root["medicationCodeableConcept"] as? JsonObject val coding = concept.codingWithSystem(RXNORM_SYSTEM) val displayName = coding?.string("display")@@ -357,24 +455,134 @@ object FhirRecords { ?: concept.anyCoding()?.string("display") ?: return null - val period = root["effectivePeriod"] as? JsonObject- val startedAt = parseDateTime(period?.string("start"))- ?: parseDateTime(root.string("effectiveDateTime"))+ val dosage = (root["dosageInstruction"] as? JsonArray)?.firstOrNull() as? JsonObject+ val repeat = ((dosage?.get("timing") as? JsonObject)?.get("repeat")) as? JsonObject+ val bounds = repeat?.get("boundsPeriod") as? JsonObject++ val startedAt = parseDateTime(root.string("authoredOn"))+ ?: parseDateTime(bounds.string("start")) ?: return null+ val endedAt = parseDateTime(bounds.string("end")) - return MedicationEntry(+ val entry = MedicationEntry( id = id, rxcui = coding?.string("code"), displayName = displayName,- status = statusFromFhir(root.string("status")),+ status = requestStatusFromFhir(root.string("status")), startedAt = startedAt,- endedAt = parseDateTime(period?.string("end")),- dosageText = (root["dosage"] as? JsonArray)- ?.firstNotNullOfOrNull { (it as? JsonObject)?.string("text") },+ endedAt = endedAt,+ dosageText = dosage?.string("text"), note = root.firstNoteText(), fhirResourceId = id, dataSourceId = dataSourceId, )+ return entry to repeat?.let { parseRepeat(it, id, startedAt, endedAt) }+ }++ private fun parseRepeat(+ repeat: JsonObject,+ medicationId: String,+ startedAt: Instant,+ endedAt: Instant?,+ ): MedicationSchedule? {+ val times = (repeat["timeOfDay"] as? JsonArray)+ ?.mapNotNull { (it as? JsonPrimitive)?.content?.let(::parseTimeOfDay) }+ .orEmpty()+ // Without clock times there is nothing to remind at, whatever else the timing says.+ if (times.isEmpty()) return null++ val unit = if (repeat.string("periodUnit") == "wk") RepeatUnit.Weekly else RepeatUnit.Daily+ 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++ return MedicationSchedule(+ id = medicationId,+ medicationId = medicationId,+ // Imported schedules arrive switched off. Someone else's record should not start a+ // phone ringing on its own.+ enabled = false,+ times = times.distinct().sorted(),+ repeatUnit = unit,+ interval = repeat["period"]?.jsonPrimitive?.intOrNull?.coerceAtLeast(1) ?: 1,+ daysOfWeek = days,+ anchorDate = startedAt.toScheduleDate(),+ endDate = endedAt?.toScheduleDate(),+ )+ }++ /** Seconds since midnight from "08:00:00", tolerating a missing seconds field. */+ private fun parseTimeOfDay(value: String): Int? {+ val parts = value.split(":")+ if (parts.size < 2) return null+ val h = parts[0].toIntOrNull() ?: return null+ val m = parts[1].toIntOrNull() ?: return null+ val s = parts.getOrNull(2)?.substringBefore('.')?.toIntOrNull() ?: 0+ return h * 3600 + m * 60 + s+ }++ /**+ * One dose actually taken, as a FHIR `MedicationStatement`.+ *+ * This is what `MedicationStatement` is for: a report that a medication was taken, as opposed to+ * the plan to take it. `MedicationAdministration` would be the precise resource for the act of+ * swallowing a tablet, but Health Connect does not accept that type, and a completed statement+ * with a single `effectiveDateTime` says the same thing in a type it does accept.+ *+ * `basedOn` points at the [MedicationRequest][medicationRequestJson] it fulfils, which is what+ * ties a dose to its regimen without needing an extension to tell the two apart.+ */+ fun doseEventJson(event: DoseEvent, medication: MedicationEntry): String = buildJsonObject {+ put("resourceType", "MedicationStatement")+ put("id", event.id)+ put("status", "completed")+ putJsonArray("basedOn") {+ add(buildJsonObject { put("reference", "MedicationRequest/${event.medicationId}") })+ }+ putJsonObject("medicationCodeableConcept") {+ if (medication.rxcui != null) {+ putJsonArray("coding") {+ add(+ buildJsonObject {+ put("system", RXNORM_SYSTEM)+ put("code", medication.rxcui)+ put("display", fullMedicationName(medication))+ }+ )+ }+ }+ put("text", fullMedicationName(medication))+ }+ putJsonObject("subject") { put("reference", "Patient/$PATIENT_RESOURCE_ID") }+ // A moment, not a period: this is one dose, not a course of them.+ put("effectiveDateTime", formatDateTime(event.takenAt))+ put("dateAsserted", formatDateTime(event.takenAt))+ medication.dosageText?.takeIf { it.isNotBlank() }?.let {+ putJsonArray("dosage") { add(buildJsonObject { put("text", it) }) }+ }+ }.toString()++ fun parseDoseEvent(data: String, dataSourceId: String): DoseEvent? {+ val root = parseObject(data) ?: return null+ if (root.string("resourceType") != "MedicationStatement") return null+ val id = root.string("id") ?: return null+ val takenAt = parseDateTime(root.string("effectiveDateTime")) ?: return null+ val medicationId = (root["basedOn"] as? JsonArray)+ ?.firstNotNullOfOrNull { (it as? JsonObject).string("reference") }+ ?.substringAfter("MedicationRequest/", "")+ ?.takeIf { it.isNotEmpty() }+ ?: return null++ return DoseEvent(+ id = id,+ medicationId = medicationId,+ takenAt = takenAt,+ fhirResourceId = id,+ dataSourceId = dataSourceId,+ ) } fun parseAllergyIntolerance(data: String, dataSourceId: String): AllergyEntry? {@@ -808,15 +1016,21 @@ object FhirRecords { private fun JsonObject.firstNoteText(): String? = (this["note"] as? JsonArray)?.firstNotNullOfOrNull { (it as? JsonObject)?.string("text") } - private fun statusToFhir(status: MedicationStatus): String = when (status) {+ /**+ * [MedicationStatus] as a `MedicationRequest.status`.+ *+ * A different value set from `MedicationStatement.status`, which is why this is not shared with+ * the dose events: a request can be `stopped`, a statement cannot.+ */+ private fun requestStatusToFhir(status: MedicationStatus): String = when (status) { MedicationStatus.Active -> "active" MedicationStatus.Completed -> "completed" MedicationStatus.Stopped -> "stopped" } - private fun statusFromFhir(status: String?): MedicationStatus = when (status) {+ private fun requestStatusFromFhir(status: String?): MedicationStatus = when (status) { "completed" -> MedicationStatus.Completed- "stopped", "not-taken", "entered-in-error" -> MedicationStatus.Stopped+ "stopped", "cancelled", "entered-in-error" -> MedicationStatus.Stopped else -> MedicationStatus.Active }
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 4497646a4e..3d19d86266 100644--- a/health/src/main/java/com/vayunmathur/health/platform/DoseActionReceiver.kt+++ b/health/src/main/java/com/vayunmathur/health/platform/DoseActionReceiver.kt@@ -1,11 +1,22 @@+@file:OptIn(kotlin.uuid.ExperimentalUuidApi::class)+ package com.vayunmathur.health.platform import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.util.Log+import com.vayunmathur.health.data.DoseEvent+import com.vayunmathur.health.data.HealthRepository+import com.vayunmathur.health.domain.FhirRecords import com.vayunmathur.health.notifications.DoseNotification import com.vayunmathur.health.service.DoseSoundService+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch+import java.time.Instant+import kotlin.uuid.Uuid /** * Handles Taken and Snooze, from either the notification actions or the full-screen reminder.@@ -22,7 +33,7 @@ class DoseActionReceiver : BroadcastReceiver() { stopRinging(context) when (intent.action) {- ACTION_TAKEN -> Log.i(TAG, "Dose taken for $medicationId")+ ACTION_TAKEN -> recordTaken(context, medicationId) ACTION_SNOOZE -> { DoseScheduler.armSnooze(context, scheduleId, medicationId, SNOOZE_MS) Log.i(TAG, "Dose for $medicationId snoozed for ${SNOOZE_MS / 60_000} minutes")@@ -30,6 +41,43 @@ class DoseActionReceiver : BroadcastReceiver() { } } + /**+ * Writes the dose locally, then mirrors it to Health Connect.+ *+ * Local first, and the mirror is allowed to fail: the alarm may have woken a process where+ * nothing has set up the Health Connect client, and losing the record of a dose the user+ * explicitly acknowledged would be much worse than an un-mirrored row. A later import reconciles.+ */+ private fun recordTaken(context: Context, medicationId: String) {+ val repository = HealthRepository.get(context)+ val pendingResult = goAsync()+ CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {+ try {+ val event = DoseEvent(+ id = Uuid.random().toString(),+ medicationId = medicationId,+ takenAt = Instant.now(),+ )+ repository.upsertDoseEvent(event)+ Log.i(TAG, "Dose taken for $medicationId")++ val medication = repository.getMedication(medicationId) ?: return@launch+ val dataSourceId = PersonalHealthRecords.dataSourceId() ?: return@launch+ val written = PersonalHealthRecords.upsert(+ dataSourceId,+ FhirRecords.doseEventJson(event, medication),+ ) ?: return@launch+ repository.upsertDoseEvent(+ event.copy(fhirResourceId = written, dataSourceId = dataSourceId)+ )+ } catch (e: Exception) {+ Log.e(TAG, "Could not record the dose for $medicationId", e)+ } finally {+ pendingResult.finish()+ }+ }+ }+ private fun stopRinging(context: Context) { DoseNotification.cancel(context) try {
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 b05c692cbd..a113b341a7 100644--- a/health/src/main/java/com/vayunmathur/health/platform/MedicalViewModel.kt+++ b/health/src/main/java/com/vayunmathur/health/platform/MedicalViewModel.kt@@ -15,6 +15,7 @@ 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.HealthProfile import com.vayunmathur.health.data.HealthRepository import com.vayunmathur.health.data.LabResultEntry@@ -546,31 +547,89 @@ class MedicalViewModel( DoseScheduler.cancel(getApplication(), it.id) } repository.deleteScheduleFor(entry.id)+ // The doses go with the medication. Leaving them would strand rows pointing at a+ // MedicationRequest that no longer exists.+ repository.deleteDosesFor(entry.id) repository.deleteMedication(entry) val dataSourceId = entry.dataSourceId val fhirId = entry.fhirResourceId if (dataSourceId != null && fhirId != null) { PersonalHealthRecords.delete( dataSourceId,- PersonalHealthRecords.medicationStatementResourceType,+ PersonalHealthRecords.medicationRequestResourceType, fhirId, ) } } } + /**+ * Writes the medication to Health Connect as a `MedicationRequest`.+ *+ * The schedule goes with it, which is what puts the reminder times in the record as+ * `dosageInstruction.timing.repeat` rather than leaving them as a private detail of this app.+ */ private suspend fun mirrorMedication(id: String) { val dataSourceId = PersonalHealthRecords.dataSourceId() ?: return val entry = repository.getMedication(id) ?: return+ val schedule = repository.getScheduleFor(id) val written = PersonalHealthRecords.upsert( dataSourceId,- FhirRecords.medicationStatementJson(entry),+ FhirRecords.medicationRequestJson(entry, schedule), ) ?: return repository.upsertMedication( entry.copy(fhirResourceId = written, dataSourceId = dataSourceId) ) } + // --- Doses taken ---------------------------------------------------------++ /** Every dose taken, newest first. */+ val doseEvents: StateFlow<List<DoseEvent>> = repository.getDoseEventsFlow()+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())++ /**+ * Records that a dose was taken, now.+ *+ * Called from the reminder's Taken action and from the medication list. Only acknowledged doses+ * are ever written — see [DoseEvent].+ */+ fun recordDoseTaken(medicationId: String, takenAt: Instant = Instant.now()) {+ viewModelScope.launch {+ val event = DoseEvent(+ id = Uuid.random().toString(),+ medicationId = medicationId,+ takenAt = takenAt,+ )+ repository.upsertDoseEvent(event)++ val dataSourceId = PersonalHealthRecords.dataSourceId() ?: return@launch+ val medication = repository.getMedication(medicationId) ?: return@launch+ val written = PersonalHealthRecords.upsert(+ dataSourceId,+ FhirRecords.doseEventJson(event, medication),+ ) ?: return@launch+ repository.upsertDoseEvent(+ event.copy(fhirResourceId = written, dataSourceId = dataSourceId)+ )+ }+ }++ fun deleteDoseEvent(event: DoseEvent) {+ viewModelScope.launch {+ repository.deleteDoseEvent(event)+ val dataSourceId = event.dataSourceId+ val fhirId = event.fhirResourceId+ if (dataSourceId != null && fhirId != null) {+ PersonalHealthRecords.delete(+ dataSourceId,+ PersonalHealthRecords.medicationStatementResourceType,+ fhirId,+ )+ }+ }+ }+ // --- Allergies and conditions -------------------------------------------- fun saveAllergyDraft() {@@ -851,11 +910,25 @@ class MedicalViewModel( } if (vaccines.isNotEmpty()) repository.upsertVaccinations(vaccines) - val meds = PersonalHealthRecords.readAll(PersonalHealthRecords.medicationsType)- .mapNotNull { resource ->- FhirRecords.parseMedicationStatement(resource.data, resource.dataSourceId)- }- if (meds.isNotEmpty()) repository.upsertMedications(meds)+ // Medications are MedicationRequests; a MedicationStatement in the same category is+ // a dose that was taken. Old records written by an earlier build are plain+ // statements with no basedOn, so they parse as neither and are skipped rather than+ // being misread as doses.+ val medResources = PersonalHealthRecords.readAll(PersonalHealthRecords.medicationsType)++ val meds = medResources.mapNotNull { resource ->+ FhirRecords.parseMedicationRequest(resource.data, resource.dataSourceId)+ }+ if (meds.isNotEmpty()) {+ repository.upsertMedications(meds.map { it.first })+ // An imported schedule arrives disabled, so this cannot start alarms on its own.+ meds.mapNotNull { it.second }.forEach { repository.upsertSchedule(it) }+ }++ val doses = medResources.mapNotNull { resource ->+ FhirRecords.parseDoseEvent(resource.data, resource.dataSourceId)+ }+ if (doses.isNotEmpty()) repository.upsertDoseEvents(doses) val allergyRows = PersonalHealthRecords.readAll(PersonalHealthRecords.allergiesType) .mapNotNull { resource ->
health/src/main/java/com/vayunmathur/health/platform/PersonalHealthRecords.kt
diff --git a/health/src/main/java/com/vayunmathur/health/platform/PersonalHealthRecords.kt b/health/src/main/java/com/vayunmathur/health/platform/PersonalHealthRecords.ktindex b85631cf46..eb332ff5aa 100644--- a/health/src/main/java/com/vayunmathur/health/platform/PersonalHealthRecords.kt+++ b/health/src/main/java/com/vayunmathur/health/platform/PersonalHealthRecords.kt@@ -199,6 +199,7 @@ object PersonalHealthRecords { val socialHistoryType: Int get() = MedicalResource.MEDICAL_RESOURCE_TYPE_SOCIAL_HISTORY val immunizationResourceType: Int get() = FhirResource.FHIR_RESOURCE_TYPE_IMMUNIZATION val medicationStatementResourceType: Int get() = FhirResource.FHIR_RESOURCE_TYPE_MEDICATION_STATEMENT+ val medicationRequestResourceType: Int get() = FhirResource.FHIR_RESOURCE_TYPE_MEDICATION_REQUEST val allergyResourceType: Int get() = FhirResource.FHIR_RESOURCE_TYPE_ALLERGY_INTOLERANCE val conditionResourceType: Int get() = FhirResource.FHIR_RESOURCE_TYPE_CONDITION val observationResourceType: Int get() = FhirResource.FHIR_RESOURCE_TYPE_OBSERVATION
health/src/main/java/com/vayunmathur/health/ui/HealthFormat.kt
diff --git a/health/src/main/java/com/vayunmathur/health/ui/HealthFormat.kt b/health/src/main/java/com/vayunmathur/health/ui/HealthFormat.ktindex f090c284a8..ba8e840447 100644--- a/health/src/main/java/com/vayunmathur/health/ui/HealthFormat.kt+++ b/health/src/main/java/com/vayunmathur/health/ui/HealthFormat.kt@@ -5,6 +5,7 @@ import com.vayunmathur.health.R import com.vayunmathur.library.ui.DateString import kotlinx.datetime.atStartOfDayIn import kotlinx.datetime.toKotlinLocalDate+import kotlinx.datetime.toKotlinLocalTime import java.time.Instant import java.time.ZoneId import kotlin.time.Duration.Companion.minutes@@ -28,6 +29,23 @@ fun Instant.toLocalDate(): kotlinx.datetime.LocalDate = */ fun medicalDateString(instant: Instant): String = DateString.dateLong(instant.toLocalDate()) +/**+ * A medical record's date and time of day.+ *+ * For the few places where the hour matters as much as the day — when a dose was taken, when the+ * next one is due. Honours the device's 12- or 24-hour setting through [DateString].+ */+fun medicalDateTimeString(instant: Instant, is24Hour: Boolean): String {+ val local = instant.atZone(ZoneId.systemDefault())+ return DateString.dateTime(+ kotlinx.datetime.LocalDateTime(+ local.toLocalDate().toKotlinLocalDate(),+ local.toLocalTime().toKotlinLocalTime(),+ ),+ is24Hour,+ )+}+ /** Joins the parts that are present with a middle dot, the app's inline detail separator. */ fun detailLine(vararg parts: String?): String = parts.filter { !it.isNullOrBlank() }.joinToString(" \u00B7 ")
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 6c38c8775b..c3cbbc9f30 100644--- a/health/src/main/java/com/vayunmathur/health/ui/MedicationPage.kt+++ b/health/src/main/java/com/vayunmathur/health/ui/MedicationPage.kt@@ -30,6 +30,8 @@ import com.vayunmathur.library.ui.EmptyState import com.vayunmathur.library.ui.ExperimentalMaterial3Api import com.vayunmathur.library.ui.FloatingActionButton import com.vayunmathur.library.ui.IconAdd+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconCheck import com.vayunmathur.library.ui.IconMedication import com.vayunmathur.library.ui.LazyListScaffold import com.vayunmathur.library.ui.ListItem@@ -41,6 +43,7 @@ import com.vayunmathur.library.ui.appBarScrollBehavior import com.vayunmathur.library.ui.itemMotion import com.vayunmathur.library.ui.rememberIs24Hour import com.vayunmathur.library.util.NavBackStack+import java.time.Instant import kotlin.time.Clock /**@@ -59,6 +62,9 @@ fun MedicationPage(backStack: NavBackStack<Route>, viewModel: MedicalViewModel) LaunchedEffect(Unit) { viewModel.importFromHealthConnect() } val schedules by viewModel.schedules.collectAsState()+ val doses by viewModel.doseEvents.collectAsState()+ // Newest dose per medication. The flow is already ordered newest first, so the first hit wins.+ val lastTaken = remember(doses) { doses.associateBy({ it.medicationId }, { it.takenAt }) } val current = entries.filter { it.status == MedicationStatus.Active } val past = entries.filter { it.status != MedicationStatus.Active } @@ -115,7 +121,15 @@ fun MedicationPage(backStack: NavBackStack<Route>, viewModel: MedicalViewModel) modifier = itemMotion(), enableStartToEnd = false, onEndToStart = { pendingDelete = entry },- ) { MedicationCard(entry, schedules[entry.id]) { openEditor(entry) } }+ ) {+ MedicationCard(+ entry = entry,+ schedule = schedules[entry.id],+ lastTaken = lastTaken[entry.id],+ onTake = { viewModel.recordDoseTaken(entry.id) },+ onClick = { openEditor(entry) },+ )+ } } if (past.isNotEmpty()) {@@ -126,7 +140,16 @@ fun MedicationPage(backStack: NavBackStack<Route>, viewModel: MedicalViewModel) modifier = itemMotion(), enableStartToEnd = false, onEndToStart = { pendingDelete = entry },- ) { MedicationCard(entry, schedules[entry.id]) { openEditor(entry) } }+ ) {+ MedicationCard(+ entry = entry,+ schedule = schedules[entry.id],+ lastTaken = lastTaken[entry.id],+ // No tick on something no longer being taken.+ onTake = null,+ onClick = { openEditor(entry) },+ )+ } } } }@@ -135,6 +158,8 @@ fun MedicationPage(backStack: NavBackStack<Route>, viewModel: MedicalViewModel) private fun MedicationCard( entry: MedicationEntry, schedule: MedicationSchedule?,+ lastTaken: Instant?,+ onTake: (() -> Unit)?, onClick: () -> Unit, ) { Card(modifier = Modifier.fillMaxWidth(), onClick = onClick) {@@ -144,14 +169,36 @@ private fun MedicationCard( }, overlineContent = { Text(medicationPeriod(entry)) }, supportingContent = {- Text(detailLine(entry.doseForm, entry.dosageText, nextDoseText(schedule)))+ Text(+ detailLine(+ entry.doseForm,+ entry.dosageText,+ lastTakenText(lastTaken),+ nextDoseText(schedule),+ )+ ) }, leadingContent = { IconMedication(tint = HealthColors.Medical) },- trailingContent = { Text(stringResource(entry.status.selectorLabelRes())) },+ trailingContent = {+ if (onTake != null) {+ // One tap to log a dose without opening anything, which is the only way this+ // gets used for a medication that has no reminder set.+ IconButton(onClick = onTake) { IconCheck(tint = HealthColors.Medical) }+ } else {+ Text(stringResource(entry.status.selectorLabelRes()))+ }+ }, ) } } +/** "Last taken …" for a medication with a recorded dose, or null when there is none. */+@Composable+private fun lastTakenText(takenAt: Instant?): String? {+ if (takenAt == null) return null+ return stringResource(R.string.last_taken, medicalDateTimeString(takenAt, rememberIs24Hour()))+}+ /** "Next dose …" for a scheduled medication, or null when it has no reminders. */ @Composable private fun nextDoseText(schedule: MedicationSchedule?): 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 0802e74218..4355b3951c 100644--- a/health/src/main/res/values/strings.xml+++ b/health/src/main/res/values/strings.xml@@ -654,4 +654,6 @@ <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>+ <!-- MedicationPage: Supporting line showing when a dose was last recorded, %1$s is a date and time -->+ <string name="last_taken">Last taken <xliff:g example="4 Mar 2026 08:00" id="when">%1$s</xliff:g></string> </resources>
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 9a0712b270..12fcd7fb3f 100644--- a/health/src/test/java/com/vayunmathur/health/domain/FhirRecordsTest.kt+++ b/health/src/test/java/com/vayunmathur/health/domain/FhirRecordsTest.kt@@ -5,9 +5,13 @@ 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@@ -149,14 +153,18 @@ class FhirRecordsTest { assertEquals(flu.id, parsed.fhirResourceId) } - // --- MedicationStatement -------------------------------------------------+ // --- MedicationRequest: the plan ------------------------------------------ @Test- fun `medication statement carries every field FHIR requires`() {- val root = parse(FhirRecords.medicationStatementJson(amoxicillin))+ fun `a medication is a plan, not a report that it was taken`() {+ val root = parse(FhirRecords.medicationRequestJson(amoxicillin)) - assertEquals("MedicationStatement", root.str("resourceType"))+ // MedicationRequest, because this is the intention to take something. A statement would+ // assert the whole course had already been consumed.+ assertEquals("MedicationRequest", root.str("resourceType")) assertEquals("completed", root.str("status"))+ assertEquals("plan", root.str("intent"))+ assertEquals("true", root.str("reportedBoolean")) assertEquals( "Patient/${FhirRecords.PATIENT_RESOURCE_ID}", root["subject"]!!.jsonObject.str("reference"),@@ -167,36 +175,162 @@ class FhirRecordsTest { assertEquals(FhirRecords.RXNORM_SYSTEM, coding.str("system")) assertEquals("308182", coding.str("code")) assertEquals("amoxicillin 250 MG Oral Capsule", coding.str("display"))-- val period = root["effectivePeriod"]!!.jsonObject- assertEquals("2026-01-10T00:00:00Z", period.str("start"))- assertEquals("2026-01-17T00:00:00Z", period.str("end"))+ assertEquals("2026-01-10T00:00:00Z", root.str("authoredOn")) } @Test- fun `an ongoing medication has no period end`() {+ fun `an ongoing medication is active`() { val ongoing = amoxicillin.copy(status = MedicationStatus.Active, endedAt = null)- val root = parse(FhirRecords.medicationStatementJson(ongoing))-- assertEquals("active", root.str("status"))- assertNull(root["effectivePeriod"]!!.jsonObject["end"])+ assertEquals("active", parse(FhirRecords.medicationRequestJson(ongoing)).str("status")) } @Test- fun `a medication statement round trips`() {- val parsed = FhirRecords.parseMedicationStatement(- FhirRecords.medicationStatementJson(amoxicillin),+ fun `a medication round trips`() {+ val parsed = FhirRecords.parseMedicationRequest(+ FhirRecords.medicationRequestJson(amoxicillin), "src-1",- )+ )?.first assertNotNull(parsed) assertEquals(amoxicillin.rxcui, parsed.rxcui) assertEquals(amoxicillin.status, parsed.status) assertEquals(amoxicillin.startedAt, parsed.startedAt)- assertEquals(amoxicillin.endedAt, parsed.endedAt) assertEquals(amoxicillin.dosageText, parsed.dosageText) } + @Test+ fun `the dose schedule travels as timing repeat`() {+ val schedule = MedicationSchedule(+ id = "sched-1",+ medicationId = amoxicillin.id,+ times = listOf(8 * 3600, 20 * 3600),+ repeatUnit = RepeatUnit.Weekly,+ interval = 2,+ // Monday and Thursday. Bit 0 is Sunday.+ daysOfWeek = (1 shl 1) or (1 shl 4),+ anchorDate = KotlinLocalDate(2026, 1, 10),+ endDate = KotlinLocalDate(2026, 3, 1),+ )+ val dosage = parse(FhirRecords.medicationRequestJson(amoxicillin, schedule))[+ "dosageInstruction"+ ]!!.jsonArray.single().jsonObject+ val repeat = dosage["timing"]!!.jsonObject["repeat"]!!.jsonObject++ assertEquals(+ listOf("08:00:00", "20:00:00"),+ (repeat["timeOfDay"] as JsonArray).map { it.jsonPrimitive.content },+ )+ assertEquals("2", repeat.str("period"))+ assertEquals("wk", repeat.str("periodUnit"))+ assertEquals("2", repeat.str("frequency"))+ assertEquals(+ listOf("mon", "thu"),+ (repeat["dayOfWeek"] as JsonArray).map { it.jsonPrimitive.content },+ )+ assertEquals("2026-03-01", repeat["boundsPeriod"]!!.jsonObject.str("end"))+ }++ @Test+ fun `a schedule round trips, but arrives switched off`() {+ val schedule = MedicationSchedule(+ id = amoxicillin.id,+ medicationId = amoxicillin.id,+ enabled = true,+ times = listOf(9 * 3600),+ repeatUnit = RepeatUnit.Daily,+ interval = 3,+ anchorDate = KotlinLocalDate(2026, 1, 10),+ )+ val parsed = FhirRecords.parseMedicationRequest(+ FhirRecords.medicationRequestJson(amoxicillin, schedule),+ "src-1",+ )?.second++ assertNotNull(parsed)+ assertEquals(listOf(9 * 3600), parsed.times)+ assertEquals(RepeatUnit.Daily, parsed.repeatUnit)+ assertEquals(3, parsed.interval)+ // Someone else's record must not start this phone ringing.+ assertEquals(false, parsed.enabled)+ }++ @Test+ fun `a medication with no schedule yields no schedule`() {+ val parsed = FhirRecords.parseMedicationRequest(+ FhirRecords.medicationRequestJson(amoxicillin),+ "src-1",+ )+ assertNotNull(parsed)+ assertNull(parsed.second)+ }++ // --- MedicationStatement: the dose actually taken --------------------------++ @Test+ fun `a taken dose is a completed statement pointing at its plan`() {+ val event = DoseEvent(+ id = "dose-1",+ medicationId = amoxicillin.id,+ takenAt = Instant.parse("2026-01-12T08:05:00Z"),+ )+ val root = parse(FhirRecords.doseEventJson(event, amoxicillin))++ assertEquals("MedicationStatement", root.str("resourceType"))+ assertEquals("completed", root.str("status"))+ // A moment, not a period - one dose rather than a course.+ assertEquals("2026-01-12T08:05:00Z", root.str("effectiveDateTime"))+ assertNull(root["effectivePeriod"])+ assertEquals(+ "MedicationRequest/${amoxicillin.id}",+ (root["basedOn"] as JsonArray).single().jsonObject.str("reference"),+ )+ }++ @Test+ fun `a dose round trips`() {+ val event = DoseEvent(+ id = "dose-1",+ medicationId = amoxicillin.id,+ takenAt = Instant.parse("2026-01-12T08:05:00Z"),+ )+ val parsed = FhirRecords.parseDoseEvent(+ FhirRecords.doseEventJson(event, amoxicillin),+ "src-1",+ )++ assertNotNull(parsed)+ assertEquals(event.medicationId, parsed.medicationId)+ assertEquals(event.takenAt, parsed.takenAt)+ }++ @Test+ fun `the plan and the dose never parse as each other`() {+ val event = DoseEvent("dose-1", amoxicillin.id, Instant.parse("2026-01-12T08:05:00Z"))+ val plan = FhirRecords.medicationRequestJson(amoxicillin)+ val dose = FhirRecords.doseEventJson(event, amoxicillin)++ assertNull(FhirRecords.parseDoseEvent(plan, "src"))+ assertNull(FhirRecords.parseMedicationRequest(dose, "src"))+ }++ @Test+ fun `a bare statement with no basedOn is not treated as a dose`() {+ // What an earlier build of this app wrote for a medication, and what a provider writes for+ // a reported medication. Neither is a dose event, and guessing would invent history.+ val bare = """+ {+ "resourceType": "MedicationStatement",+ "id": "legacy-1",+ "status": "active",+ "medicationCodeableConcept": { "text": "Metformin" },+ "subject": { "reference": "Patient/other" },+ "effectiveDateTime": "2024-06-01"+ }+ """.trimIndent()++ assertNull(FhirRecords.parseDoseEvent(bare, "hospital"))+ }+ // --- Reading what other systems write ------------------------------------ @Test@@ -228,16 +362,17 @@ class FhirRecordsTest { fun `unknown statuses are treated as still being taken`() { val provider = """ {- "resourceType": "MedicationStatement",+ "resourceType": "MedicationRequest", "id": "provider-2", "status": "unknown",+ "intent": "order", "medicationCodeableConcept": { "text": "Metformin" }, "subject": { "reference": "Patient/other" },- "effectiveDateTime": "2024-06"+ "authoredOn": "2024-06" } """.trimIndent() - val parsed = FhirRecords.parseMedicationStatement(provider, "hospital")+ val parsed = FhirRecords.parseMedicationRequest(provider, "hospital")?.first assertNotNull(parsed) assertEquals(MedicationStatus.Active, parsed.status)@@ -249,7 +384,7 @@ class FhirRecordsTest { 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.parseMedicationStatement(FhirRecords.immunizationJson(flu), "src"))+ assertNull(FhirRecords.parseMedicationRequest(FhirRecords.immunizationJson(flu), "src")) } @Test