health: medication planned end, timing on record, reminder toggle
- Commit
de47de281ee55bef996ff9ebec878bf67e9dbce2- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-02 03:02 UTC (4 days ago)
- Parents
2b251b9
The medication record now owns its course plan and dosage timing, and reminders are literally just a toggle on that record. Schema (DB v12 to v13, migration in data/Record.kt, schema 13.json): MedicationEntry gains plannedEndDate (LocalDate?), doseTimes, repeatUnit, doseInterval, daysOfWeek, scheduleAnchorDate and remindersEnabled. The 12-to-13 migration adds those columns, copies every existing MedicationSchedule row onto its medication (times/repeat/interval/weekdays/anchor, enabled into remindersEnabled, and the schedule endDate into plannedEndDate, so existing reminders keep firing on the same days and stop on the same date), then drops the MedicationSchedule table and its index. Medications with no schedule keep the column defaults. RepeatUnit moves onto MedicalRecords.kt beside MedicationEntry, MedicationSchedule.kt is deleted, and Converters moves out of Record.kt into HealthConverters.kt to keep Record.kt under the file-length lint limit. Behaviour: DoseSchedule computes the next dose straight from a MedicationEntry and only fires while remindersEnabled is on, the status is still Active (Taking), and the planned end date has not passed. DoseScheduler arms per medication, the boot receiver re-arms getMedicationsWithReminders(), and the dose receiver re-arms from the medication it fetched. Saving a draft writes the timing and toggle onto the entry, clears plannedEndDate when the course is finished/stopped, forces reminders off while not Taking, and re-arms or cancels from the stored row. FHIR MedicationRequest export/import carries the timing and planned end on the entry itself (boundsPeriod end is endedAt for finished courses and plannedEndDate for ongoing ones); imports still arrive with reminders off, and importing over an existing row preserves the user's toggle and planned end. UI: the When section shows Planned end date only while the status is Taking, opening the existing MedicalDatePicker dialog route with allowClear, plus an X (IconClose) on the PickerField itself that clears the date in place (PickerField gains an optional onClear). The old ScheduleSection splits into DosageTimingSection (times, interval, repeat unit, weekdays, on the medication form regardless of reminders) and ReminderToggleSection (only the Remind-me switch and the full-screen-intent warning); the reminder Until field and the reminders_until string are gone. No new dialogs were added, so no new DialogAsRoute destinations were needed. Tests: DoseScheduleTest pins firing per medication timing, stopping after the medication planned end date, and never firing when the toggle is off or the medication is no longer being taken. MedicationFormTest pins that Planned end date is shown only while Taking and that the X clears it. MedicalOpsTest pins that the planned end saves while Taking and is cleared (with reminders forced off) when finished. MigrationsTest is extended to v13 and pins that 12-to-13 copies schedule timing and end date onto the medication and drops the schedule table. Existing FHIR, scheduler, receiver, DAO, repository and compose tests are updated to the record-owned timing model. Verified in this worktree: ./gradlew :health:lint green (lintVitalRelease was SKIPPED by Gradle in that run), and :health:testDevUnitTest targeted re-runs of the touched suites green; the first full run had one failure caused by the new section title (fixed by renaming it to Dose timing) and one unrelated recipe-editor flake that passes standalone.
Diff
health/AGENTS.md
diff --git a/health/AGENTS.md b/health/AGENTS.mdindex 5ed16a2153..861571ace5 100644--- a/health/AGENTS.md+++ b/health/AGENTS.md@@ -14,9 +14,9 @@ _Install: ./install health (dev by default)._ **Purpose:** Offline health-metric manager (Google Fit replacement) — activity/vitals/body/exercise/sleep/hydration/nutrition plus FHIR medical records, backed by Health Connect. No account, no cloud sync. **Key features:** - Per-metric dashboards with charts/history (`GenericLineChart`/`GenericBarChart`, hypnogram for sleep)-- Medications with dose schedules + exact reminders (`DoseScheduler`, `DoseSoundService`, boot-rescheduled); vaccinations from bundled CVX, drugs from RxNorm; card attachments (PDF/photo)+- Medications carry their own dosage timing (dose times/repeat) and an optional planned end date (shown only while Taking), with exact reminders as a literal on/off toggle on the medication record (`DoseScheduler`, `DoseSoundService`, boot-rescheduled; reminders fire per the medication timing and stop after its planned end date — there is no separate reminder schedule/end date); vaccinations from bundled CVX, drugs from RxNorm; card attachments (PDF/photo) - Food logging against a bundled database + search API; AI insights via the on-device OpenAssistant model; file export-**Architecture / data-flow:** Dialogs that act on a record/metric are `Route.…Dialog` destinations (`DialogPage()` entries in `ui/NavigationEntries.kt`) pushed from clicks, with stateless content under `ui/dialogs/`; the ingredient search→quantity chain in `RecipeEditorPage` is the one local exception (see its `DIALOG LOCAL EXCEPTION` marker). Screenshot coverage lives in `src/screenshotTest` `MetadataPreviews` (stateless screens: Today/Nutrition/Body/metric detail/nutrition breakdown/recipe list+editor/sleep/exercise + date-time and simple dialog routes); VM-draft routes are exempted per-route in `Route.kt`. `ui/` Today + record pages → `platform/MedicalViewModel` (+ per-area `Medical*Ops`) → `data/HealthRepository` over Room (`Record`, `MedicationSchedule`, `MedicalRecords`) synced with Health Connect; `domain/` holds pure FHIR (Observations, Medication, Immunization, Allergy/Condition) + `DoseSchedule`; reminders flow `DoseScheduler` → receivers → `DoseReminderActivity` + `service/DoseSoundService`.+**Architecture / data-flow:** Dialogs that act on a record/metric are `Route.…Dialog` destinations (`DialogPage()` entries in `ui/NavigationEntries.kt`) pushed from clicks, with stateless content under `ui/dialogs/`; the ingredient search→quantity chain in `RecipeEditorPage` is the one local exception (see its `DIALOG LOCAL EXCEPTION` marker). Screenshot coverage lives in `src/screenshotTest` `MetadataPreviews` (stateless screens: Today/Nutrition/Body/metric detail/nutrition breakdown/recipe list+editor/sleep/exercise + date-time and simple dialog routes); VM-draft routes are exempted per-route in `Route.kt`. `ui/` Today + record pages → `platform/MedicalViewModel` (+ per-area `Medical*Ops`) → `data/HealthRepository` over Room (`Record`, `MedicalRecords`; dosage timing/planned end/reminder toggle are columns on `MedicationEntry`) synced with Health Connect; `domain/` holds pure FHIR (Observations, Medication, Immunization, Allergy/Condition) + `DoseSchedule` (next-dose arithmetic over a `MedicationEntry`); reminders flow `DoseScheduler` (armed per medication) → receivers → `DoseReminderActivity` + `service/DoseSoundService`. DB is v13, with the medication timing/end/toggle columns living on `MedicationEntry` (migration 12→13 in `data/Record.kt` preserves existing schedules onto that record). **Entry points + reading order:** `MainActivity.kt` → `ui/TodayPage.kt` → `platform/MedicalViewModel.kt` → `data/HealthRepository.kt` → `domain/FhirRecords.kt` → `platform/DoseScheduler.kt`. **Gotchas:** - Day views use half-open local-calendar ranges (`HealthChartData.dayRange`, DAO `startTime in [start, end)`, bucketed by start): DST days are 23/25h, midnight point records belong to the new day, and intervals crossing midnight count on their start day. Day-tab line metrics average their hourly averages; bar metrics sum their hourly sums; basal metabolic rate (stored kcal/day) is an averaged line metric, while Today hydration converts stored litres to ml. Month/year tabs bucket bar metrics into weekly/monthly sums: their per-day average divides the period total by the calendar days in the month/year, and a history row's goal is the daily goal scaled by the days its bucket covers (line metrics keep averaging and comparing bucket averages directly).@@ -31,9 +31,9 @@ _Install: ./install health (dev by default)._ - com/vayunmathur/health/Navigation.kt ### data/ — Room entities + repository - com/vayunmathur/health/data/HealthRepository.kt+- com/vayunmathur/health/data/HealthConverters.kt — Room type converters (`Converters`) - com/vayunmathur/health/data/Record.kt - com/vayunmathur/health/data/NutritionScaling.kt-- com/vayunmathur/health/data/MedicationSchedule.kt - com/vayunmathur/health/data/MedicalRecords.kt - com/vayunmathur/health/data/FoodModels.kt - com/vayunmathur/health/data/ReferenceCatalog.kt@@ -126,7 +126,8 @@ _Install: ./install health (dev by default)._ - com/vayunmathur/health/ui/components/AttachmentChip.kt - com/vayunmathur/health/ui/components/MedicalStorageNotice.kt - com/vayunmathur/health/ui/components/PickerField.kt-- com/vayunmathur/health/ui/components/ScheduleSection.kt+- com/vayunmathur/health/ui/components/DosageTimingSection.kt — dosage timing fields on the medication form+- com/vayunmathur/health/ui/components/ReminderToggleSection.kt — the literal reminder on/off toggle (+ full-screen-intent warning) - com/vayunmathur/health/ui/components/SectionLabel.kt - com/vayunmathur/health/ui/components/AnswerPickerDialog.kt
health/schemas/com.vayunmathur.health.data.HealthDatabase/13.json
diff --git a/health/schemas/com.vayunmathur.health.data.HealthDatabase/13.json b/health/schemas/com.vayunmathur.health.data.HealthDatabase/13.jsonnew file mode 100644index 0000000000..a5187638d6--- /dev/null+++ b/health/schemas/com.vayunmathur.health.data.HealthDatabase/13.json@@ -0,0 +1,1591 @@+{+ "formatVersion": 1,+ "database": {+ "version": 13,+ "identityHash": "bfc511caff484001c3a714d7ebd9186b",+ "entities": [+ {+ "tableName": "Record",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `index` INTEGER NOT NULL, `type` TEXT NOT NULL, `startTime` INTEGER NOT NULL, `endTime` INTEGER NOT NULL, `value` REAL NOT NULL, `secondaryValue` REAL NOT NULL, `metadata` TEXT, `primaryKey` TEXT NOT NULL, `nutrition_protein` REAL, `nutrition_carbohydrates` REAL, `nutrition_fat` REAL, `nutrition_fiber` REAL, `nutrition_sugar` REAL, `nutrition_sodium` REAL, `nutrition_biotin` REAL, `nutrition_caffeine` REAL, `nutrition_calcium` REAL, `nutrition_chloride` REAL, `nutrition_cholesterol` REAL, `nutrition_chromium` REAL, `nutrition_copper` REAL, `nutrition_folate` REAL, `nutrition_folicAcid` REAL, `nutrition_iodine` REAL, `nutrition_iron` REAL, `nutrition_magnesium` REAL, `nutrition_manganese` REAL, `nutrition_molybdenum` REAL, `nutrition_monounsaturatedFat` REAL, `nutrition_niacin` REAL, `nutrition_pantothenicAcid` REAL, `nutrition_phosphorus` REAL, `nutrition_polyunsaturatedFat` REAL, `nutrition_potassium` REAL, `nutrition_riboflavin` REAL, `nutrition_saturatedFat` REAL, `nutrition_selenium` REAL, `nutrition_thiamin` REAL, `nutrition_transFat` REAL, `nutrition_unsaturatedFat` REAL, `nutrition_vitaminA` REAL, `nutrition_vitaminB12` REAL, `nutrition_vitaminB6` REAL, `nutrition_vitaminC` REAL, `nutrition_vitaminD` REAL, `nutrition_vitaminE` REAL, `nutrition_vitaminK` REAL, `nutrition_zinc` REAL, `nutrition_calories` REAL, `sleep_awakeDurationMillis` INTEGER, `sleep_remDurationMillis` INTEGER, `sleep_lightDurationMillis` INTEGER, `sleep_deepDurationMillis` INTEGER, `sleep_unknownDurationMillis` INTEGER, `sleep_stagesJson` TEXT, `exercise_exerciseType` INTEGER, `exercise_title` TEXT, `exercise_notes` TEXT, `exercise_segmentsJson` TEXT, `exercise_lapsJson` TEXT, `exercise_hasRoute` INTEGER, PRIMARY KEY(`primaryKey`))",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "index",+ "columnName": "index",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "type",+ "columnName": "type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "startTime",+ "columnName": "startTime",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "endTime",+ "columnName": "endTime",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "value",+ "columnName": "value",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "secondaryValue",+ "columnName": "secondaryValue",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "metadata",+ "columnName": "metadata",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "primaryKey",+ "columnName": "primaryKey",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.protein",+ "columnName": "nutrition_protein",+ "affinity": "REAL"+ },+ {+ "fieldPath": "nutritionData.carbohydrates",+ "columnName": "nutrition_carbohydrates",+ "affinity": "REAL"+ },+ {+ "fieldPath": "nutritionData.fat",+ "columnName": "nutrition_fat",+ "affinity": "REAL"+ },+ {+ "fieldPath": "nutritionData.fiber",+ "columnName": "nutrition_fiber",+ "affinity": "REAL"+ },+ {+ "fieldPath": "nutritionData.sugar",+ "columnName": "nutrition_sugar",+ "affinity": "REAL"+ },+ {+ "fieldPath": "nutritionData.sodium",+ "columnName": "nutrition_sodium",+ "affinity": "REAL"+ },+ {+ "fieldPath": "nutritionData.biotin",+ "columnName": "nutrition_biotin",+ "affinity": "REAL"+ },+ {+ "fieldPath": "nutritionData.caffeine",+ "columnName": "nutrition_caffeine",+ "affinity": "REAL"+ },+ {+ "fieldPath": "nutritionData.calcium",+ "columnName": "nutrition_calcium",+ "affinity": "REAL"+ },+ {+ "fieldPath": "nutritionData.chloride",+ "columnName": "nutrition_chloride",+ "affinity": "REAL"+ },+ {+ "fieldPath": "nutritionData.cholesterol",+ "columnName": "nutrition_cholesterol",+ "affinity": "REAL"+ },+ {+ "fieldPath": "nutritionData.chromium",+ "columnName": "nutrition_chromium",+ "affinity": "REAL"+ },+ {+ "fieldPath": "nutritionData.copper",+ "columnName": "nutrition_copper",+ "affinity": "REAL"+ },+ {+ "fieldPath": "nutritionData.folate",+ "columnName": "nutrition_folate",+ "affinity": "REAL"+ },+ {+ "fieldPath": "nutritionData.folicAcid",+ "columnName": "nutrition_folicAcid",+ "affinity": "REAL"+ },+ {+ "fieldPath": "nutritionData.iodine",+ "columnName": "nutrition_iodine",+ "affinity": "REAL"+ },+ {+ "fieldPath": "nutritionData.iron",+ "columnName": "nutrition_iron",+ "affinity": "REAL"+ },+ {+ "fieldPath": "nutritionData.magnesium",+ "columnName": "nutrition_magnesium",+ "affinity": "REAL"+ },+ {+ "fieldPath": "nutritionData.manganese",+ "columnName": "nutrition_manganese",+ "affinity": "REAL"+ },+ {+ "fieldPath": "nutritionData.molybdenum",+ "columnName": "nutrition_molybdenum",+ "affinity": "REAL"+ },+ {+ "fieldPath": "nutritionData.monounsaturatedFat",+ "columnName": "nutrition_monounsaturatedFat",+ "affinity": "REAL"+ },+ {+ "fieldPath": "nutritionData.niacin",+ "columnName": "nutrition_niacin",+ "affinity": "REAL"+ },+ {+ "fieldPath": "nutritionData.pantothenicAcid",+ "columnName": "nutrition_pantothenicAcid",+ "affinity": "REAL"+ },+ {+ "fieldPath": "nutritionData.phosphorus",+ "columnName": "nutrition_phosphorus",+ "affinity": "REAL"+ },+ {+ "fieldPath": "nutritionData.polyunsaturatedFat",+ "columnName": "nutrition_polyunsaturatedFat",+ "affinity": "REAL"+ },+ {+ "fieldPath": "nutritionData.potassium",+ "columnName": "nutrition_potassium",+ "affinity": "REAL"+ },+ {+ "fieldPath": "nutritionData.riboflavin",+ "columnName": "nutrition_riboflavin",+ "affinity": "REAL"+ },+ {+ "fieldPath": "nutritionData.saturatedFat",+ "columnName": "nutrition_saturatedFat",+ "affinity": "REAL"+ },+ {+ "fieldPath": "nutritionData.selenium",+ "columnName": "nutrition_selenium",+ "affinity": "REAL"+ },+ {+ "fieldPath": "nutritionData.thiamin",+ "columnName": "nutrition_thiamin",+ "affinity": "REAL"+ },+ {+ "fieldPath": "nutritionData.transFat",+ "columnName": "nutrition_transFat",+ "affinity": "REAL"+ },+ {+ "fieldPath": "nutritionData.unsaturatedFat",+ "columnName": "nutrition_unsaturatedFat",+ "affinity": "REAL"+ },+ {+ "fieldPath": "nutritionData.vitaminA",+ "columnName": "nutrition_vitaminA",+ "affinity": "REAL"+ },+ {+ "fieldPath": "nutritionData.vitaminB12",+ "columnName": "nutrition_vitaminB12",+ "affinity": "REAL"+ },+ {+ "fieldPath": "nutritionData.vitaminB6",+ "columnName": "nutrition_vitaminB6",+ "affinity": "REAL"+ },+ {+ "fieldPath": "nutritionData.vitaminC",+ "columnName": "nutrition_vitaminC",+ "affinity": "REAL"+ },+ {+ "fieldPath": "nutritionData.vitaminD",+ "columnName": "nutrition_vitaminD",+ "affinity": "REAL"+ },+ {+ "fieldPath": "nutritionData.vitaminE",+ "columnName": "nutrition_vitaminE",+ "affinity": "REAL"+ },+ {+ "fieldPath": "nutritionData.vitaminK",+ "columnName": "nutrition_vitaminK",+ "affinity": "REAL"+ },+ {+ "fieldPath": "nutritionData.zinc",+ "columnName": "nutrition_zinc",+ "affinity": "REAL"+ },+ {+ "fieldPath": "nutritionData.calories",+ "columnName": "nutrition_calories",+ "affinity": "REAL"+ },+ {+ "fieldPath": "sleepData.awakeDurationMillis",+ "columnName": "sleep_awakeDurationMillis",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "sleepData.remDurationMillis",+ "columnName": "sleep_remDurationMillis",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "sleepData.lightDurationMillis",+ "columnName": "sleep_lightDurationMillis",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "sleepData.deepDurationMillis",+ "columnName": "sleep_deepDurationMillis",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "sleepData.unknownDurationMillis",+ "columnName": "sleep_unknownDurationMillis",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "sleepData.stagesJson",+ "columnName": "sleep_stagesJson",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "exerciseData.exerciseType",+ "columnName": "exercise_exerciseType",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "exerciseData.title",+ "columnName": "exercise_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "exerciseData.notes",+ "columnName": "exercise_notes",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "exerciseData.segmentsJson",+ "columnName": "exercise_segmentsJson",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "exerciseData.lapsJson",+ "columnName": "exercise_lapsJson",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "exerciseData.hasRoute",+ "columnName": "exercise_hasRoute",+ "affinity": "INTEGER"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "primaryKey"+ ]+ },+ "indices": [+ {+ "name": "index_Record_type_startTime_endTime",+ "unique": false,+ "columnNames": [+ "type",+ "startTime",+ "endTime"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_Record_type_startTime_endTime` ON `${TABLE_NAME}` (`type`, `startTime`, `endTime`)"+ }+ ]+ },+ {+ "tableName": "Ingredient",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `originalName` TEXT NOT NULL, `customName` TEXT, `isRecipe` INTEGER NOT NULL, `nutrition_protein` REAL NOT NULL, `nutrition_carbohydrates` REAL NOT NULL, `nutrition_fat` REAL NOT NULL, `nutrition_fiber` REAL NOT NULL, `nutrition_sugar` REAL NOT NULL, `nutrition_sodium` REAL NOT NULL, `nutrition_biotin` REAL NOT NULL, `nutrition_caffeine` REAL NOT NULL, `nutrition_calcium` REAL NOT NULL, `nutrition_chloride` REAL NOT NULL, `nutrition_cholesterol` REAL NOT NULL, `nutrition_chromium` REAL NOT NULL, `nutrition_copper` REAL NOT NULL, `nutrition_folate` REAL NOT NULL, `nutrition_folicAcid` REAL NOT NULL, `nutrition_iodine` REAL NOT NULL, `nutrition_iron` REAL NOT NULL, `nutrition_magnesium` REAL NOT NULL, `nutrition_manganese` REAL NOT NULL, `nutrition_molybdenum` REAL NOT NULL, `nutrition_monounsaturatedFat` REAL NOT NULL, `nutrition_niacin` REAL NOT NULL, `nutrition_pantothenicAcid` REAL NOT NULL, `nutrition_phosphorus` REAL NOT NULL, `nutrition_polyunsaturatedFat` REAL NOT NULL, `nutrition_potassium` REAL NOT NULL, `nutrition_riboflavin` REAL NOT NULL, `nutrition_saturatedFat` REAL NOT NULL, `nutrition_selenium` REAL NOT NULL, `nutrition_thiamin` REAL NOT NULL, `nutrition_transFat` REAL NOT NULL, `nutrition_unsaturatedFat` REAL NOT NULL, `nutrition_vitaminA` REAL NOT NULL, `nutrition_vitaminB12` REAL NOT NULL, `nutrition_vitaminB6` REAL NOT NULL, `nutrition_vitaminC` REAL NOT NULL, `nutrition_vitaminD` REAL NOT NULL, `nutrition_vitaminE` REAL NOT NULL, `nutrition_vitaminK` REAL NOT NULL, `nutrition_zinc` REAL NOT NULL, `nutrition_calories` REAL NOT NULL, PRIMARY KEY(`id`))",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "originalName",+ "columnName": "originalName",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "customName",+ "columnName": "customName",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "isRecipe",+ "columnName": "isRecipe",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.protein",+ "columnName": "nutrition_protein",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.carbohydrates",+ "columnName": "nutrition_carbohydrates",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.fat",+ "columnName": "nutrition_fat",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.fiber",+ "columnName": "nutrition_fiber",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.sugar",+ "columnName": "nutrition_sugar",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.sodium",+ "columnName": "nutrition_sodium",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.biotin",+ "columnName": "nutrition_biotin",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.caffeine",+ "columnName": "nutrition_caffeine",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.calcium",+ "columnName": "nutrition_calcium",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.chloride",+ "columnName": "nutrition_chloride",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.cholesterol",+ "columnName": "nutrition_cholesterol",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.chromium",+ "columnName": "nutrition_chromium",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.copper",+ "columnName": "nutrition_copper",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.folate",+ "columnName": "nutrition_folate",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.folicAcid",+ "columnName": "nutrition_folicAcid",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.iodine",+ "columnName": "nutrition_iodine",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.iron",+ "columnName": "nutrition_iron",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.magnesium",+ "columnName": "nutrition_magnesium",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.manganese",+ "columnName": "nutrition_manganese",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.molybdenum",+ "columnName": "nutrition_molybdenum",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.monounsaturatedFat",+ "columnName": "nutrition_monounsaturatedFat",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.niacin",+ "columnName": "nutrition_niacin",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.pantothenicAcid",+ "columnName": "nutrition_pantothenicAcid",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.phosphorus",+ "columnName": "nutrition_phosphorus",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.polyunsaturatedFat",+ "columnName": "nutrition_polyunsaturatedFat",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.potassium",+ "columnName": "nutrition_potassium",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.riboflavin",+ "columnName": "nutrition_riboflavin",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.saturatedFat",+ "columnName": "nutrition_saturatedFat",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.selenium",+ "columnName": "nutrition_selenium",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.thiamin",+ "columnName": "nutrition_thiamin",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.transFat",+ "columnName": "nutrition_transFat",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.unsaturatedFat",+ "columnName": "nutrition_unsaturatedFat",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.vitaminA",+ "columnName": "nutrition_vitaminA",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.vitaminB12",+ "columnName": "nutrition_vitaminB12",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.vitaminB6",+ "columnName": "nutrition_vitaminB6",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.vitaminC",+ "columnName": "nutrition_vitaminC",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.vitaminD",+ "columnName": "nutrition_vitaminD",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.vitaminE",+ "columnName": "nutrition_vitaminE",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.vitaminK",+ "columnName": "nutrition_vitaminK",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.zinc",+ "columnName": "nutrition_zinc",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "nutritionData.calories",+ "columnName": "nutrition_calories",+ "affinity": "REAL",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ }+ },+ {+ "tableName": "Recipe",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `name` TEXT NOT NULL, PRIMARY KEY(`id`))",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ }+ },+ {+ "tableName": "ServingUnit",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `ingredientId` TEXT, `recipeId` TEXT, `name` TEXT NOT NULL, `grams` REAL NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`ingredientId`) REFERENCES `Ingredient`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`recipeId`) REFERENCES `Recipe`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "ingredientId",+ "columnName": "ingredientId",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "recipeId",+ "columnName": "recipeId",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "grams",+ "columnName": "grams",+ "affinity": "REAL",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_ServingUnit_ingredientId",+ "unique": false,+ "columnNames": [+ "ingredientId"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_ServingUnit_ingredientId` ON `${TABLE_NAME}` (`ingredientId`)"+ },+ {+ "name": "index_ServingUnit_recipeId",+ "unique": false,+ "columnNames": [+ "recipeId"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_ServingUnit_recipeId` ON `${TABLE_NAME}` (`recipeId`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "Ingredient",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "ingredientId"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "Recipe",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "recipeId"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "RecipeIngredient",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `recipeId` TEXT NOT NULL, `ingredientId` TEXT NOT NULL, `quantity` REAL NOT NULL, `unitId` TEXT NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`recipeId`) REFERENCES `Recipe`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`ingredientId`) REFERENCES `Ingredient`(`id`) ON UPDATE NO ACTION ON DELETE RESTRICT , FOREIGN KEY(`unitId`) REFERENCES `ServingUnit`(`id`) ON UPDATE NO ACTION ON DELETE RESTRICT )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "recipeId",+ "columnName": "recipeId",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "ingredientId",+ "columnName": "ingredientId",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "quantity",+ "columnName": "quantity",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "unitId",+ "columnName": "unitId",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_RecipeIngredient_recipeId",+ "unique": false,+ "columnNames": [+ "recipeId"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_RecipeIngredient_recipeId` ON `${TABLE_NAME}` (`recipeId`)"+ },+ {+ "name": "index_RecipeIngredient_ingredientId",+ "unique": false,+ "columnNames": [+ "ingredientId"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_RecipeIngredient_ingredientId` ON `${TABLE_NAME}` (`ingredientId`)"+ },+ {+ "name": "index_RecipeIngredient_unitId",+ "unique": false,+ "columnNames": [+ "unitId"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_RecipeIngredient_unitId` ON `${TABLE_NAME}` (`unitId`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "Recipe",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "recipeId"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "Ingredient",+ "onDelete": "RESTRICT",+ "onUpdate": "NO ACTION",+ "columns": [+ "ingredientId"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "ServingUnit",+ "onDelete": "RESTRICT",+ "onUpdate": "NO ACTION",+ "columns": [+ "unitId"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "VaccinationEntry",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `cvxCode` TEXT, `displayName` TEXT NOT NULL, `occurredAt` INTEGER NOT NULL, `lotNumber` TEXT, `site` TEXT, `route` TEXT, `doseQuantity` TEXT, `performer` TEXT, `note` TEXT, `fhirResourceId` TEXT, `dataSourceId` TEXT, PRIMARY KEY(`id`))",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "cvxCode",+ "columnName": "cvxCode",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "displayName",+ "columnName": "displayName",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "occurredAt",+ "columnName": "occurredAt",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lotNumber",+ "columnName": "lotNumber",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "site",+ "columnName": "site",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "route",+ "columnName": "route",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "doseQuantity",+ "columnName": "doseQuantity",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "performer",+ "columnName": "performer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "note",+ "columnName": "note",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "fhirResourceId",+ "columnName": "fhirResourceId",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "dataSourceId",+ "columnName": "dataSourceId",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_VaccinationEntry_occurredAt",+ "unique": false,+ "columnNames": [+ "occurredAt"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_VaccinationEntry_occurredAt` ON `${TABLE_NAME}` (`occurredAt`)"+ }+ ]+ },+ {+ "tableName": "MedicationEntry",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `rxcui` TEXT, `displayName` TEXT NOT NULL, `strength` TEXT, `doseForm` TEXT, `status` TEXT NOT NULL, `startedAt` INTEGER NOT NULL, `endedAt` INTEGER, `plannedEndDate` INTEGER, `doseTimes` TEXT NOT NULL, `repeatUnit` TEXT NOT NULL, `doseInterval` INTEGER NOT NULL, `daysOfWeek` INTEGER NOT NULL, `scheduleAnchorDate` INTEGER, `remindersEnabled` INTEGER NOT NULL, `dosageText` TEXT, `note` TEXT, `fhirResourceId` TEXT, `dataSourceId` TEXT, PRIMARY KEY(`id`))",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "rxcui",+ "columnName": "rxcui",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "displayName",+ "columnName": "displayName",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "strength",+ "columnName": "strength",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "doseForm",+ "columnName": "doseForm",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "startedAt",+ "columnName": "startedAt",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "endedAt",+ "columnName": "endedAt",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "plannedEndDate",+ "columnName": "plannedEndDate",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "doseTimes",+ "columnName": "doseTimes",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "repeatUnit",+ "columnName": "repeatUnit",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "doseInterval",+ "columnName": "doseInterval",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "daysOfWeek",+ "columnName": "daysOfWeek",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "scheduleAnchorDate",+ "columnName": "scheduleAnchorDate",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "remindersEnabled",+ "columnName": "remindersEnabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "dosageText",+ "columnName": "dosageText",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "note",+ "columnName": "note",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "fhirResourceId",+ "columnName": "fhirResourceId",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "dataSourceId",+ "columnName": "dataSourceId",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_MedicationEntry_startedAt",+ "unique": false,+ "columnNames": [+ "startedAt"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_MedicationEntry_startedAt` ON `${TABLE_NAME}` (`startedAt`)"+ }+ ]+ },+ {+ "tableName": "MedicalAttachment",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `vaccinationId` TEXT NOT NULL, `fileName` TEXT NOT NULL, `displayName` TEXT NOT NULL, `mimeType` TEXT NOT NULL, `sizeBytes` INTEGER NOT NULL, `importedAt` INTEGER NOT NULL, PRIMARY KEY(`id`))",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "vaccinationId",+ "columnName": "vaccinationId",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "fileName",+ "columnName": "fileName",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "displayName",+ "columnName": "displayName",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "mimeType",+ "columnName": "mimeType",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "sizeBytes",+ "columnName": "sizeBytes",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "importedAt",+ "columnName": "importedAt",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_MedicalAttachment_vaccinationId",+ "unique": false,+ "columnNames": [+ "vaccinationId"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_MedicalAttachment_vaccinationId` ON `${TABLE_NAME}` (`vaccinationId`)"+ }+ ]+ },+ {+ "tableName": "AllergyEntry",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `rxcui` TEXT, `displayName` TEXT NOT NULL, `category` TEXT NOT NULL, `criticality` TEXT NOT NULL, `reaction` TEXT, `onsetAt` INTEGER, `recordedAt` INTEGER NOT NULL, `note` TEXT, `fhirResourceId` TEXT, `dataSourceId` TEXT, PRIMARY KEY(`id`))",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "rxcui",+ "columnName": "rxcui",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "displayName",+ "columnName": "displayName",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "category",+ "columnName": "category",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "criticality",+ "columnName": "criticality",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "reaction",+ "columnName": "reaction",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "onsetAt",+ "columnName": "onsetAt",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "recordedAt",+ "columnName": "recordedAt",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "note",+ "columnName": "note",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "fhirResourceId",+ "columnName": "fhirResourceId",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "dataSourceId",+ "columnName": "dataSourceId",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_AllergyEntry_recordedAt",+ "unique": false,+ "columnNames": [+ "recordedAt"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_AllergyEntry_recordedAt` ON `${TABLE_NAME}` (`recordedAt`)"+ }+ ]+ },+ {+ "tableName": "ConditionEntry",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `icd10Code` TEXT, `displayName` TEXT NOT NULL, `status` TEXT NOT NULL, `onsetAt` INTEGER NOT NULL, `resolvedAt` INTEGER, `note` TEXT, `fhirResourceId` TEXT, `dataSourceId` TEXT, PRIMARY KEY(`id`))",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "icd10Code",+ "columnName": "icd10Code",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "displayName",+ "columnName": "displayName",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "onsetAt",+ "columnName": "onsetAt",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "resolvedAt",+ "columnName": "resolvedAt",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "note",+ "columnName": "note",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "fhirResourceId",+ "columnName": "fhirResourceId",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "dataSourceId",+ "columnName": "dataSourceId",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_ConditionEntry_onsetAt",+ "unique": false,+ "columnNames": [+ "onsetAt"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_ConditionEntry_onsetAt` ON `${TABLE_NAME}` (`onsetAt`)"+ }+ ]+ },+ {+ "tableName": "LabResultEntry",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `loincCode` TEXT, `displayName` TEXT NOT NULL, `value` REAL, `valueText` TEXT, `unit` TEXT, `referenceLow` REAL, `referenceHigh` REAL, `takenAt` INTEGER NOT NULL, `note` TEXT, `fhirResourceId` TEXT, `dataSourceId` TEXT, PRIMARY KEY(`id`))",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "loincCode",+ "columnName": "loincCode",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "displayName",+ "columnName": "displayName",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "value",+ "columnName": "value",+ "affinity": "REAL"+ },+ {+ "fieldPath": "valueText",+ "columnName": "valueText",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "unit",+ "columnName": "unit",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "referenceLow",+ "columnName": "referenceLow",+ "affinity": "REAL"+ },+ {+ "fieldPath": "referenceHigh",+ "columnName": "referenceHigh",+ "affinity": "REAL"+ },+ {+ "fieldPath": "takenAt",+ "columnName": "takenAt",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "note",+ "columnName": "note",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "fhirResourceId",+ "columnName": "fhirResourceId",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "dataSourceId",+ "columnName": "dataSourceId",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_LabResultEntry_takenAt",+ "unique": false,+ "columnNames": [+ "takenAt"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_LabResultEntry_takenAt` ON `${TABLE_NAME}` (`takenAt`)"+ }+ ]+ },+ {+ "tableName": "HealthProfile",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `pregnancyStatus` TEXT NOT NULL, `dueDate` INTEGER, `pregnancyRecordedAt` INTEGER, `pregnancyFhirId` TEXT, `smokingStatus` TEXT NOT NULL, `smokingRecordedAt` INTEGER, `smokingFhirId` TEXT, `dataSourceId` TEXT, PRIMARY KEY(`id`))",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "pregnancyStatus",+ "columnName": "pregnancyStatus",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "dueDate",+ "columnName": "dueDate",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "pregnancyRecordedAt",+ "columnName": "pregnancyRecordedAt",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "pregnancyFhirId",+ "columnName": "pregnancyFhirId",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "smokingStatus",+ "columnName": "smokingStatus",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "smokingRecordedAt",+ "columnName": "smokingRecordedAt",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "smokingFhirId",+ "columnName": "smokingFhirId",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "dataSourceId",+ "columnName": "dataSourceId",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ }+ },+ {+ "tableName": "ProfileAnswer",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`loincCode` TEXT NOT NULL, `answerCode` TEXT NOT NULL, `recordedAt` INTEGER NOT NULL, `fhirResourceId` TEXT, `dataSourceId` TEXT, PRIMARY KEY(`loincCode`))",+ "fields": [+ {+ "fieldPath": "loincCode",+ "columnName": "loincCode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "answerCode",+ "columnName": "answerCode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "recordedAt",+ "columnName": "recordedAt",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "fhirResourceId",+ "columnName": "fhirResourceId",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "dataSourceId",+ "columnName": "dataSourceId",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "loincCode"+ ]+ }+ },+ {+ "tableName": "DoseEvent",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `medicationId` TEXT NOT NULL, `takenAt` INTEGER NOT NULL, `fhirResourceId` TEXT, `dataSourceId` TEXT, PRIMARY KEY(`id`))",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "medicationId",+ "columnName": "medicationId",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "takenAt",+ "columnName": "takenAt",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "fhirResourceId",+ "columnName": "fhirResourceId",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "dataSourceId",+ "columnName": "dataSourceId",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_DoseEvent_medicationId_takenAt",+ "unique": false,+ "columnNames": [+ "medicationId",+ "takenAt"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_DoseEvent_medicationId_takenAt` ON `${TABLE_NAME}` (`medicationId`, `takenAt`)"+ }+ ]+ },+ {+ "tableName": "DeletedMedicalResource",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`kind` TEXT NOT NULL, `dataSourceId` TEXT NOT NULL, `fhirResourceId` TEXT NOT NULL, `fhirResourceType` INTEGER NOT NULL, `retryDelete` INTEGER NOT NULL, PRIMARY KEY(`kind`, `dataSourceId`, `fhirResourceId`))",+ "fields": [+ {+ "fieldPath": "kind",+ "columnName": "kind",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "dataSourceId",+ "columnName": "dataSourceId",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "fhirResourceId",+ "columnName": "fhirResourceId",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "fhirResourceType",+ "columnName": "fhirResourceType",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryDelete",+ "columnName": "retryDelete",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "kind",+ "dataSourceId",+ "fhirResourceId"+ ]+ }+ },+ {+ "tableName": "PendingMirror",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`kind` TEXT NOT NULL, `rowId` TEXT NOT NULL, PRIMARY KEY(`kind`, `rowId`))",+ "fields": [+ {+ "fieldPath": "kind",+ "columnName": "kind",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "rowId",+ "columnName": "rowId",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "kind",+ "rowId"+ ]+ }+ }+ ],+ "setupQueries": [+ "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",+ "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'bfc511caff484001c3a714d7ebd9186b')"+ ]+ }+}\ No newline at end of file
health/src/main/java/com/vayunmathur/health/data/HealthConverters.kt
diff --git a/health/src/main/java/com/vayunmathur/health/data/HealthConverters.kt b/health/src/main/java/com/vayunmathur/health/data/HealthConverters.ktnew file mode 100644index 0000000000..59e56ab8d7--- /dev/null+++ b/health/src/main/java/com/vayunmathur/health/data/HealthConverters.kt@@ -0,0 +1,41 @@+package com.vayunmathur.health.data++import androidx.room3.ColumnTypeConverter+import java.time.Instant++/** Type representing converters. */+class Converters {+ @ColumnTypeConverter+ fun fromTimestamp(value: Long?): Instant? = value?.let { Instant.ofEpochMilli(it) }++ @ColumnTypeConverter+ fun dateToTimestamp(date: Instant?): Long? = date?.toEpochMilli()++ @ColumnTypeConverter+ fun toTS(date: kotlin.time.Instant): Long = date.toEpochMilliseconds()++ @ColumnTypeConverter+ fun fromTS(timestamp: Long): kotlin.time.Instant = kotlin.time.Instant.fromEpochMilliseconds(timestamp)++ /** Dose times, stored as comma-separated seconds-since-midnight. */+ @ColumnTypeConverter+ fun fromIntList(value: List<Int>): String = value.joinToString(",")++ @ColumnTypeConverter+ fun toIntList(value: String): List<Int> =+ if (value.isBlank()) emptyList() else value.split(",").mapNotNull { it.trim().toIntOrNull() }++ @ColumnTypeConverter+ fun fromLocalDate(date: kotlinx.datetime.LocalDate): Long = date.toEpochDays()++ @ColumnTypeConverter+ fun toLocalDate(days: Long): kotlinx.datetime.LocalDate =+ kotlinx.datetime.LocalDate.fromEpochDays(days)++ @ColumnTypeConverter+ fun fromLocalDateNullable(date: kotlinx.datetime.LocalDate?): Long? = date?.toEpochDays()++ @ColumnTypeConverter+ fun toLocalDateNullable(days: Long?): kotlinx.datetime.LocalDate? =+ days?.let { kotlinx.datetime.LocalDate.fromEpochDays(it) }+}
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 7b7e36eacd..baf41ede80 100644--- a/health/src/main/java/com/vayunmathur/health/data/HealthRepository.kt+++ b/health/src/main/java/com/vayunmathur/health/data/HealthRepository.kt@@ -22,7 +22,6 @@ class HealthRepository private constructor(context: Context) : private val dao get() = db.healthDao() private val medicalDao get() = db.medicalDao()- private val scheduleDao get() = db.scheduleDao() // ------------------------------------------------------------------ // Flow passthroughs — keep DAO names so callers migrating off `HealthAPI.db.healthDao()` stay trivial@@ -180,14 +179,10 @@ class HealthRepository private constructor(context: Context) : suspend fun getAttachmentsFor(vaccinationId: String): List<MedicalAttachment> = medicalDao.getAttachmentsFor(vaccinationId) - // Dose schedules- suspend fun upsertSchedule(schedule: MedicationSchedule) = scheduleDao.upsertSchedule(schedule)- suspend fun deleteScheduleFor(medicationId: String) = scheduleDao.deleteScheduleFor(medicationId)- suspend fun getScheduleFor(medicationId: String): MedicationSchedule? =- scheduleDao.getScheduleFor(medicationId)- suspend fun getSchedule(id: String): MedicationSchedule? = scheduleDao.getSchedule(id)- fun getSchedulesFlow(): Flow<List<MedicationSchedule>> = scheduleDao.getSchedulesFlow()- suspend fun getEnabledSchedules(): List<MedicationSchedule> = scheduleDao.getEnabledSchedules()+ // Reminders are a toggle on MedicationEntry (see remindersEnabled there);+ // the medications that need an alarm armed are read from that table.+ suspend fun getReminderMedications(): List<MedicationEntry> =+ medicalDao.getMedicationsWithReminders() // Allergies and conditions suspend fun upsertAllergy(entry: AllergyEntry) = medicalDao.upsertAllergy(entry)
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 b33874db33..fadca3b066 100644--- a/health/src/main/java/com/vayunmathur/health/data/MedicalRecords.kt+++ b/health/src/main/java/com/vayunmathur/health/data/MedicalRecords.kt@@ -11,6 +11,7 @@ import androidx.room3.Query import androidx.room3.Update import kotlinx.coroutines.flow.Flow import java.time.Instant+import kotlinx.datetime.LocalDate /** * A single immunisation, mirrored to Health Connect as a FHIR `Immunization`.@@ -39,6 +40,9 @@ data class VaccinationEntry( /** Whether a medication is still being taken. Maps to FHIR `MedicationRequest.status`. */ enum class MedicationStatus { Active, Completed, Stopped } +/** Whether [MedicationEntry.doseInterval] counts days or weeks. */+enum class RepeatUnit { Daily, Weekly }+ /** * A medication the user takes or has taken, mirrored to Health Connect as a FHIR * `MedicationRequest`. Same nullable-FHIR-columns arrangement as [VaccinationEntry].@@ -54,11 +58,36 @@ data class MedicationEntry( val status: MedicationStatus = MedicationStatus.Active, val startedAt: Instant, val endedAt: Instant? = null,+ /**+ * Optional planned last day of the course, shown only while [status] is+ * [MedicationStatus.Active] ("Taking"). Reminders stop after this date;+ * it is not [endedAt], which records when a finished course actually ended.+ */+ val plannedEndDate: LocalDate? = null,+ /** Seconds since midnight, one entry per dose, ascending. The dosage timing itself. */+ val doseTimes: List<Int> = emptyList(),+ val repeatUnit: RepeatUnit = RepeatUnit.Daily,+ /** Every N days or every N weeks, according to [repeatUnit]. Always at least 1. */+ val doseInterval: Int = 1,+ /** Seven-bit mask, bit 0 = Sunday. Only meaningful when [repeatUnit] is Weekly. */+ val daysOfWeek: Int = 0,+ /** The date [doseInterval] counts from; null means it counts from [startedAt]. */+ val scheduleAnchorDate: LocalDate? = null,+ /**+ * The reminder toggle. Reminders are literally just this flag: when on,+ * they fire per [doseTimes]/[repeatUnit]/[doseInterval]/[daysOfWeek] and+ * stop after [plannedEndDate]. There is no separate reminder schedule.+ */+ val remindersEnabled: Boolean = false, val dosageText: String? = null, val note: String? = null, val fhirResourceId: String? = null, val dataSourceId: String? = null,-)+) {+ /** Whether reminders should fire for this record right now, ignoring the time of day. */+ val remindersActive: Boolean+ get() = remindersEnabled && status == MedicationStatus.Active+} /** * A PDF or photo attached to a vaccination — typically a photograph of a vaccination card.@@ -310,6 +339,10 @@ interface MedicalDao { @Query("SELECT * FROM MedicationEntry WHERE fhirResourceId = :fhirResourceId") suspend fun findMedicationsByFhirId(fhirResourceId: String): List<MedicationEntry> + /** Medications whose reminder toggle is on and that are still being taken — alarms to arm. */+ @Query("SELECT * FROM MedicationEntry WHERE remindersEnabled = 1 AND status = 'Active'")+ suspend fun getMedicationsWithReminders(): List<MedicationEntry>+ // --- Attachments ------------------------------------------------------- @Insert(onConflict = OnConflictStrategy.REPLACE)
health/src/main/java/com/vayunmathur/health/data/MedicationSchedule.kt
diff --git a/health/src/main/java/com/vayunmathur/health/data/MedicationSchedule.kt b/health/src/main/java/com/vayunmathur/health/data/MedicationSchedule.ktdeleted file mode 100644index 13137dc879..0000000000--- a/health/src/main/java/com/vayunmathur/health/data/MedicationSchedule.kt+++ /dev/null@@ -1,78 +0,0 @@-package com.vayunmathur.health.data--import androidx.room3.Dao-import androidx.room3.Delete-import androidx.room3.Entity-import androidx.room3.Index-import androidx.room3.Insert-import androidx.room3.OnConflictStrategy-import androidx.room3.PrimaryKey-import androidx.room3.Query-import kotlinx.coroutines.flow.Flow-import kotlinx.datetime.LocalDate--/** Whether [MedicationSchedule.interval] counts days or weeks. */-enum class RepeatUnit { Daily, Weekly }--/**- * When a medication should be taken, and therefore when to remind.- *- * Deliberately smaller than an RFC-5545 recurrence rule. The clock app's model — one time and a- * weekday mask — cannot say "twice a day" or "every other week", and calendar's `RRule` covers- * BYSETPOS, BYYEARDAY and BYWEEKNO that no medication regimen needs and is in any case private to- * that app. Between [times], [interval] and [daysOfWeek] this covers the realistic space:- *- * - every other week, Mon and Thu, 08:00 and 20:00 → Weekly, 2, {Mon,Thu}, [08:00, 20:00]- * - every 3 days at 09:00 → Daily, 3, [09:00]- * - twice daily → Daily, 1, [08:00, 20:00]- *- * At most one per medication, and deleting the medication deletes it.- */-@Entity(indices = [Index(value = ["medicationId"], unique = true)])-data class MedicationSchedule(- @PrimaryKey val id: String,- val medicationId: String,- val enabled: Boolean = true,- /** Seconds since midnight, one entry per dose, ascending. */- val times: List<Int> = emptyList(),- val repeatUnit: RepeatUnit = RepeatUnit.Daily,- /** Every N days or every N weeks. Always at least 1. */- val interval: Int = 1,- /** Seven-bit mask, bit 0 = Sunday. Only meaningful when [repeatUnit] is Weekly. */- val daysOfWeek: Int = 0,- /**- * The date the interval counts from.- *- * Without it "every other week" has no meaning — there is nothing to say which week is week- * zero. Set to the day the schedule was created and left alone thereafter.- */- val anchorDate: LocalDate,- val endDate: LocalDate? = null,-)--/** Contract for schedule dao. */-@Dao-interface ScheduleDao {-- @Insert(onConflict = OnConflictStrategy.REPLACE)- suspend fun upsertSchedule(schedule: MedicationSchedule)-- @Delete- suspend fun deleteSchedule(schedule: MedicationSchedule)-- @Query("DELETE FROM MedicationSchedule WHERE medicationId = :medicationId")- suspend fun deleteScheduleFor(medicationId: String)-- @Query("SELECT * FROM MedicationSchedule WHERE medicationId = :medicationId")- suspend fun getScheduleFor(medicationId: String): MedicationSchedule?-- @Query("SELECT * FROM MedicationSchedule")- fun getSchedulesFlow(): Flow<List<MedicationSchedule>>-- /** Everything that needs an alarm armed — used on boot and after a time-zone change. */- @Query("SELECT * FROM MedicationSchedule WHERE enabled = 1")- suspend fun getEnabledSchedules(): List<MedicationSchedule>-- @Query("SELECT * FROM MedicationSchedule WHERE id = :id")- suspend fun getSchedule(id: String): MedicationSchedule?-}
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 3a2612d2a8..bbf9ae7d37 100644--- a/health/src/main/java/com/vayunmathur/health/data/Record.kt+++ b/health/src/main/java/com/vayunmathur/health/data/Record.kt@@ -1,5 +1,4 @@ package com.vayunmathur.health.data-import androidx.room3.ColumnTypeConverter import androidx.room3.ColumnTypeConverters import androidx.room3.Dao import androidx.room3.Database@@ -400,11 +399,11 @@ interface HealthDao { entities = [ Record::class, Ingredient::class, Recipe::class, ServingUnit::class, RecipeIngredient::class, VaccinationEntry::class, MedicationEntry::class, MedicalAttachment::class,- MedicationSchedule::class, AllergyEntry::class, ConditionEntry::class,+ AllergyEntry::class, ConditionEntry::class, LabResultEntry::class, HealthProfile::class, ProfileAnswer::class, DoseEvent::class, DeletedMedicalResource::class, PendingMirror::class, ],- version = 12,+ version = 13, exportSchema = true ) /** Health Database: a room database implementation for health database. */@@ -412,7 +411,6 @@ interface HealthDao { abstract class HealthDatabase : RoomDatabase() { abstract fun healthDao(): HealthDao abstract fun medicalDao(): MedicalDao- abstract fun scheduleDao(): ScheduleDao /** Shared constants and helpers for HealthDatabase. */ companion object : com.vayunmathur.library.util.DatabaseMigrations {@@ -756,44 +754,36 @@ abstract class HealthDatabase : RoomDatabase() { "SELECT '$kind', id FROM $table WHERE fhirResourceId IS NULL" ) }+ },+ // v12 -> v13: dosage timing and the planned end date move onto+ // MedicationEntry itself; reminders become just the+ // remindersEnabled toggle on that record. Copy every existing+ // schedule's timing into its medication (and its endDate into+ // plannedEndDate, so existing reminders keep firing on the same+ // days and stop on the same date), then drop the schedule table.+ // Medications with no schedule keep the column defaults.+ Migration(12, 13) {+ it.execSQL("ALTER TABLE MedicationEntry ADD COLUMN plannedEndDate INTEGER")+ it.execSQL("ALTER TABLE MedicationEntry ADD COLUMN doseTimes TEXT NOT NULL DEFAULT ''")+ it.execSQL("ALTER TABLE MedicationEntry ADD COLUMN repeatUnit TEXT NOT NULL DEFAULT 'Daily'")+ it.execSQL("ALTER TABLE MedicationEntry ADD COLUMN doseInterval INTEGER NOT NULL DEFAULT 1")+ it.execSQL("ALTER TABLE MedicationEntry ADD COLUMN daysOfWeek INTEGER NOT NULL DEFAULT 0")+ it.execSQL("ALTER TABLE MedicationEntry ADD COLUMN scheduleAnchorDate INTEGER")+ it.execSQL("ALTER TABLE MedicationEntry ADD COLUMN remindersEnabled INTEGER NOT NULL DEFAULT 0")+ it.execSQL(+ "UPDATE MedicationEntry SET " ++ "doseTimes = (SELECT times FROM MedicationSchedule WHERE MedicationSchedule.medicationId = MedicationEntry.id), " ++ "repeatUnit = (SELECT repeatUnit FROM MedicationSchedule WHERE MedicationSchedule.medicationId = MedicationEntry.id), " ++ "doseInterval = (SELECT interval FROM MedicationSchedule WHERE MedicationSchedule.medicationId = MedicationEntry.id), " ++ "daysOfWeek = (SELECT daysOfWeek FROM MedicationSchedule WHERE MedicationSchedule.medicationId = MedicationEntry.id), " ++ "scheduleAnchorDate = (SELECT anchorDate FROM MedicationSchedule WHERE MedicationSchedule.medicationId = MedicationEntry.id), " ++ "remindersEnabled = (SELECT enabled FROM MedicationSchedule WHERE MedicationSchedule.medicationId = MedicationEntry.id), " ++ "plannedEndDate = (SELECT endDate FROM MedicationSchedule WHERE MedicationSchedule.medicationId = MedicationEntry.id) " ++ "WHERE EXISTS (SELECT 1 FROM MedicationSchedule WHERE MedicationSchedule.medicationId = MedicationEntry.id)"+ )+ it.execSQL("DROP INDEX IF EXISTS index_MedicationSchedule_medicationId")+ it.execSQL("DROP TABLE IF EXISTS MedicationSchedule") } ) } }--/** Type representing converters. */-class Converters {- @ColumnTypeConverter- fun fromTimestamp(value: Long?): Instant? = value?.let { Instant.ofEpochMilli(it) }-- @ColumnTypeConverter- fun dateToTimestamp(date: Instant?): Long? = date?.toEpochMilli()-- @ColumnTypeConverter- fun toTS(date: kotlin.time.Instant): Long = date.toEpochMilliseconds()-- @ColumnTypeConverter- fun fromTS(timestamp: Long): kotlin.time.Instant = kotlin.time.Instant.fromEpochMilliseconds(timestamp)-- /** Dose times, stored as comma-separated seconds-since-midnight. */- @ColumnTypeConverter- fun fromIntList(value: List<Int>): String = value.joinToString(",")-- @ColumnTypeConverter- fun toIntList(value: String): List<Int> =- if (value.isBlank()) emptyList() else value.split(",").mapNotNull { it.trim().toIntOrNull() }-- @ColumnTypeConverter- fun fromLocalDate(date: kotlinx.datetime.LocalDate): Long = date.toEpochDays()-- @ColumnTypeConverter- fun toLocalDate(days: Long): kotlinx.datetime.LocalDate =- kotlinx.datetime.LocalDate.fromEpochDays(days)-- @ColumnTypeConverter- fun fromLocalDateNullable(date: kotlinx.datetime.LocalDate?): Long? = date?.toEpochDays()-- @ColumnTypeConverter- fun toLocalDateNullable(days: Long?): kotlinx.datetime.LocalDate? =- days?.let { kotlinx.datetime.LocalDate.fromEpochDays(it) }-}
health/src/main/java/com/vayunmathur/health/domain/DoseSchedule.kt
diff --git a/health/src/main/java/com/vayunmathur/health/domain/DoseSchedule.kt b/health/src/main/java/com/vayunmathur/health/domain/DoseSchedule.ktindex 756e16771a..5074874550 100644--- a/health/src/main/java/com/vayunmathur/health/domain/DoseSchedule.kt+++ b/health/src/main/java/com/vayunmathur/health/domain/DoseSchedule.kt@@ -1,6 +1,6 @@ package com.vayunmathur.health.domain -import com.vayunmathur.health.data.MedicationSchedule+import com.vayunmathur.health.data.MedicationEntry import com.vayunmathur.health.data.RepeatUnit import kotlinx.datetime.DayOfWeek import kotlinx.datetime.LocalDate@@ -15,7 +15,12 @@ import kotlinx.datetime.toLocalDateTime import kotlin.time.Instant /**- * Works out when the next dose of a [MedicationSchedule] falls due.+ * Works out when the next dose of a medication falls due, from the dosage+ * timing stored on the [MedicationEntry] itself.+ *+ * Reminders are just the `remindersEnabled` toggle on that record: the next+ * dose exists only while the toggle is on, the medication is still being+ * taken, and the planned end date (if any) has not passed. * * Pure: no Android, no database, no clock of its own — [nextDose] takes the moment to search from. * That is deliberate, because this is the part of the reminder feature most able to be quietly@@ -29,50 +34,54 @@ object DoseSchedule { /** How far ahead to look before giving up. Longer than any sane interval. */ private const val SEARCH_DAYS = 366 * 2 + /** The date interval counting starts from: the explicit anchor, else the course start. */+ fun anchorDate(medication: MedicationEntry): LocalDate =+ medication.scheduleAnchorDate ?: medication.startedAt.toScheduleDate()+ /**- * The first dose due strictly after [from], or null if the schedule is finished or unusable.+ * The first dose due strictly after [from], or null if there is none. * * Strictly after, so re-arming from inside the alarm that just fired cannot pick the same * instant again and spin. */ fun nextDose(- schedule: MedicationSchedule,+ medication: MedicationEntry, from: Instant, timeZone: TimeZone = TimeZone.currentSystemDefault(), ): Instant? {- if (!isUsable(schedule)) return null+ if (!isUsable(medication)) return null val startDate = from.toLocalDateTime(timeZone).date var date = startDate repeat(SEARCH_DAYS) {- val endDate = schedule.endDate+ val endDate = medication.plannedEndDate if (endDate != null && date > endDate) return null - firstDoseOn(schedule, date, from, timeZone)?.let { return it }+ firstDoseOn(medication, date, from, timeZone)?.let { return it } date = date.plus(1, DateTimeUnit.DAY) } return null } - /** Guards that reject a schedule before any date arithmetic runs. */- private fun isUsable(schedule: MedicationSchedule): Boolean {- if (!schedule.enabled) return false- if (schedule.times.filter { it in 0 until SECONDS_PER_DAY }.isEmpty()) return false- if (schedule.interval < 1) return false- if (schedule.repeatUnit == RepeatUnit.Weekly && schedule.daysOfWeek == 0) return false+ /** Guards that reject a medication's timing before any date arithmetic runs. */+ private fun isUsable(medication: MedicationEntry): Boolean {+ if (!medication.remindersActive) return false+ if (medication.doseTimes.filter { it in 0 until SECONDS_PER_DAY }.isEmpty()) return false+ if (medication.doseInterval < 1) return false+ if (medication.repeatUnit == RepeatUnit.Weekly && medication.daysOfWeek == 0) return false return true } /** The first dose due on [date] strictly after [from], or null if none that day. */ private fun firstDoseOn(- schedule: MedicationSchedule,+ medication: MedicationEntry, date: LocalDate, from: Instant, timeZone: TimeZone, ): Instant? {- if (!isDoseDay(schedule, date)) return null- val times = schedule.times.filter { it in 0 until SECONDS_PER_DAY }.sorted()+ if (!isDoseDay(medication, date)) return null+ val times = medication.doseTimes.filter { it in 0 until SECONDS_PER_DAY }.sorted() if (times.isEmpty()) return null for (seconds in times) { val candidate = LocalDateTime(date, LocalTime.fromSecondOfDay(seconds))@@ -82,24 +91,25 @@ object DoseSchedule { return null } - /** Whether [date] is a day this schedule calls for, ignoring the time of day. */- fun isDoseDay(schedule: MedicationSchedule, date: LocalDate): Boolean {- if (date < schedule.anchorDate) return false- schedule.endDate?.let { if (date > it) return false }+ /** Whether [date] is a day this medication's timing calls for, ignoring the time of day. */+ fun isDoseDay(medication: MedicationEntry, date: LocalDate): Boolean {+ val anchor = anchorDate(medication)+ if (date < anchor) return false+ medication.plannedEndDate?.let { if (date > it) return false } - return when (schedule.repeatUnit) {+ return when (medication.repeatUnit) { RepeatUnit.Daily -> {- val elapsed = date.toEpochDays() - schedule.anchorDate.toEpochDays()- elapsed % schedule.interval == 0L+ val elapsed = date.toEpochDays() - anchor.toEpochDays()+ elapsed % medication.doseInterval == 0L } RepeatUnit.Weekly -> {- if (!schedule.daysOfWeek.hasDay(date.dayOfWeek)) return false+ if (!medication.daysOfWeek.hasDay(date.dayOfWeek)) return false // Count in whole weeks from the week the anchor falls in, not from the anchor day // itself: "every other week on Mon and Thu" has to treat both of those as the same // week even though they are three days apart.- val elapsedWeeks = weekIndex(date) - weekIndex(schedule.anchorDate)- elapsedWeeks % schedule.interval == 0L+ val elapsedWeeks = weekIndex(date) - weekIndex(anchor)+ elapsedWeeks % medication.doseInterval == 0L } } }
health/src/main/java/com/vayunmathur/health/domain/FhirMedication.kt
diff --git a/health/src/main/java/com/vayunmathur/health/domain/FhirMedication.kt b/health/src/main/java/com/vayunmathur/health/domain/FhirMedication.ktindex 124bc22e02..3107332a5c 100644--- a/health/src/main/java/com/vayunmathur/health/domain/FhirMedication.kt+++ b/health/src/main/java/com/vayunmathur/health/domain/FhirMedication.kt@@ -2,7 +2,6 @@ package com.vayunmathur.health.domain import com.vayunmathur.health.data.DoseEvent import com.vayunmathur.health.data.MedicationEntry-import com.vayunmathur.health.data.MedicationSchedule import com.vayunmathur.health.data.MedicationStatus import com.vayunmathur.health.data.RepeatUnit import kotlinx.serialization.json.JsonArray@@ -31,11 +30,10 @@ import kotlinx.datetime.LocalDate as KotlinLocalDate * `intent` is `plan` rather than `order` because nobody prescribed this — it is the user's own * account of what they intend to take. The course dates always travel as * `dosageInstruction.timing.repeat.boundsPeriod`, since MedicationRequest has no other field for- * them; a [schedule] adds the reminder times to the same `repeat`.+ * them; the dosage timing on the entry itself adds the dose times to the same `repeat`. */ internal fun medicationRequestJson( entry: MedicationEntry,- schedule: MedicationSchedule? = null, ): String = buildJsonObject { put("resourceType", "MedicationRequest") put("id", entry.fhirId())@@ -51,7 +49,7 @@ internal fun medicationRequestJson( add( buildJsonObject { entry.dosageText?.takeIf { it.isNotBlank() }?.let { put("text", it) }- putJsonObject("timing") { putRepeat(entry, schedule) }+ putJsonObject("timing") { putRepeat(entry) } } ) }@@ -86,51 +84,52 @@ private fun JsonObjectBuilder.putMedicationConcept(entry: MedicationEntry) { * and chosen weekdays become `dayOfWeek`. */ -/** Times of day and the derived frequency for a schedule's repeat. */+/** Times of day and the derived frequency for the entry's repeat. */ private fun JsonObjectBuilder.putScheduleTimes(- schedule: MedicationSchedule,+ entry: MedicationEntry, weekly: Boolean, doseDays: Int, ) {- if (schedule.times.isEmpty()) return+ if (entry.doseTimes.isEmpty()) return putJsonArray("timeOfDay") {- schedule.times.sorted().forEach { add(JsonPrimitive(formatTimeOfDay(it))) }+ entry.doseTimes.sorted().forEach { add(JsonPrimitive(formatTimeOfDay(it))) } }- // frequency counts doses per period, so a weekly schedule multiplies its times of+ // frequency counts doses per period, so a weekly timing multiplies its times of // day by the number of days it falls on. if (!weekly || doseDays > 0) {- put("frequency", schedule.times.size * (if (weekly) doseDays else 1))+ put("frequency", entry.doseTimes.size * (if (weekly) doseDays else 1)) } }-private fun JsonObjectBuilder.putRepeat(entry: MedicationEntry, schedule: MedicationSchedule?) {+private fun JsonObjectBuilder.putRepeat(entry: MedicationEntry) { putJsonObject("repeat") { putJsonObject("boundsPeriod") { put("start", formatClinicalDate(entry.startedAt))- // A finished course ends when it ended. An ongoing one ends when its reminders do,- // if they are set to.+ // A finished course ends when it ended. An ongoing one ends on its+ // planned end date, if it has one. val end = entry.endedAt?.takeIf { entry.status != MedicationStatus.Active } ?.let { formatClinicalDate(it) }- ?: schedule?.endDate?.let { formatScheduleDate(it) }+ ?: entry.plannedEndDate?.takeIf { entry.status == MedicationStatus.Active }+ ?.let { formatScheduleDate(it) } end?.let { put("end", it) } }- if (schedule == null) return@putJsonObject+ if (entry.doseTimes.isEmpty()) return@putJsonObject - val weekly = schedule.repeatUnit == RepeatUnit.Weekly- val doseDays = Integer.bitCount(schedule.daysOfWeek and ALL_DAYS_MASK)- putScheduleTimes(schedule, weekly, doseDays)- put("period", schedule.interval)+ val weekly = entry.repeatUnit == RepeatUnit.Weekly+ val doseDays = Integer.bitCount(entry.daysOfWeek and ALL_DAYS_MASK)+ putScheduleTimes(entry, weekly, doseDays)+ put("period", entry.doseInterval) put("periodUnit", if (weekly) "wk" else "d") if (weekly && doseDays > 0) { putJsonArray("dayOfWeek") { FHIR_DAYS.forEachIndexed { index, day ->- if (schedule.daysOfWeek and (1 shl index) != 0) add(JsonPrimitive(day))+ if (entry.daysOfWeek and (1 shl index) != 0) add(JsonPrimitive(day)) } } } } } -/** Bit 0 is Sunday, matching `MedicationSchedule.daysOfWeek`. */+/** Bit 0 is Sunday, matching `MedicationEntry.daysOfWeek`. */ private val FHIR_DAYS = listOf("sun", "mon", "tue", "wed", "thu", "fri", "sat") private const val ALL_DAYS_MASK = 0x7F @@ -174,9 +173,10 @@ private fun JsonObject.medicationName(): Pair<String, String?>? { /** * A medication regimen read back from a `MedicationRequest`. *- * Returns the entry and, when the request carries a `timing.repeat` this app can represent, the- * schedule behind it — a provider's instructions are worth keeping rather than flattening to a- * date range. The entry's `id` is the FHIR id; the importer assigns the local row id.+ * When the request carries a `timing.repeat` this app can represent, its times+ * land on the entry's own dosage timing — a provider's instructions are worth+ * keeping rather than flattening to a date range. The entry's `id` is the FHIR+ * id; the importer assigns the local row id. */ /** The shared medication header: root, id, display name and RxCUI. */@@ -198,7 +198,7 @@ private fun medHeader(data: String, type: String): MedHeader? { internal fun parseMedicationRequest( data: String, dataSourceId: String,-): Pair<MedicationEntry, MedicationSchedule?>? {+): MedicationEntry? { val header = medHeader(data, "MedicationRequest") ?: return null val root = header.root val id = header.id@@ -216,22 +216,48 @@ internal fun parseMedicationRequest( ?: return null val boundsEnd = parseDateTime(bounds.string("end")) - val entry = MedicationEntry(+ val timing = repeat?.let { parseRepeat(it, startedAt, boundsEnd) }+ return MedicationEntry( id = id, rxcui = rxcui, displayName = displayName, status = status, startedAt = startedAt,- // An ongoing course's end is only planned, and belongs to the reminders.+ // An ongoing course's end is only planned, so it lands on plannedEndDate. endedAt = boundsEnd?.takeIf { status != MedicationStatus.Active },+ plannedEndDate = if (status == MedicationStatus.Active) {+ timing?.plannedEndDate ?: boundsEnd?.toScheduleDateOrNull()+ } else {+ timing?.plannedEndDate+ },+ doseTimes = timing?.doseTimes.orEmpty(),+ repeatUnit = timing?.repeatUnit ?: RepeatUnit.Daily,+ doseInterval = timing?.doseInterval ?: 1,+ daysOfWeek = timing?.daysOfWeek ?: 0,+ scheduleAnchorDate = timing?.anchorDate,+ // Imported timings arrive with reminders off. Someone else's record+ // should not start a phone ringing on its own.+ remindersEnabled = false, dosageText = dosage?.string("text"), note = root.firstNoteText(), fhirResourceId = id, dataSourceId = dataSourceId, )- return entry to repeat?.let { parseRepeat(it, id, startedAt, boundsEnd) } } +/** This instant as a schedule date, or null when there is none. */+private fun Instant?.toScheduleDateOrNull(): KotlinLocalDate? = this?.toScheduleDate()++/** Dosage timing read from a FHIR `Timing.repeat`, before it lands on an entry. */+private data class ParsedTiming(+ val doseTimes: List<Int>,+ val repeatUnit: RepeatUnit,+ val doseInterval: Int,+ val daysOfWeek: Int,+ val anchorDate: KotlinLocalDate,+ val plannedEndDate: KotlinLocalDate?,+)+ /** * A medication a provider reports the patient as taking, from a `MedicationStatement` that is not * a dose against one of this app's plans.@@ -303,10 +329,9 @@ private fun repeatUnitInterval( } private fun parseRepeat( repeat: JsonObject,- medicationId: String, startedAt: Instant, endsAt: Instant?,-): MedicationSchedule? {+): ParsedTiming? { val times = (repeat["timeOfDay"] as? JsonArray) ?.mapNotNull { (it as? JsonPrimitive)?.content?.let(::parseTimeOfDay) } .orEmpty()@@ -328,18 +353,13 @@ private fun parseRepeat( val (unit, interval) = repeatUnitInterval(repeat.string("periodUnit"), days, parsedInterval) ?: return null - 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(),+ return ParsedTiming(+ doseTimes = times.distinct().sorted(), repeatUnit = unit,- interval = interval,+ doseInterval = interval, daysOfWeek = days, anchorDate = startedAt.toScheduleDate(),- endDate = endsAt?.toScheduleDate(),+ plannedEndDate = endsAt?.toScheduleDate(), ) } @@ -352,7 +372,7 @@ private fun parseTimeOfDay(value: String): Int? { val s = parts.getOrNull(2)?.substringBefore('.')?.toIntOrNull() ?: 0 // FHIR timings come from other systems; an out-of-range clock time such as // "24:00" or "08:60" is not a dose time. Returning it as seconds-since-- // midnight would be stored on the schedule and later crash the editor's+ // midnight would be stored on the entry and later crash the editor's // LocalTime.fromSecondOfDay rendering, so reject it like any other // unparseable value. if (h !in 0..23 || m !in 0..59 || s !in 0..59) return null
health/src/main/java/com/vayunmathur/health/domain/FhirRecords.kt
diff --git a/health/src/main/java/com/vayunmathur/health/domain/FhirRecords.kt b/health/src/main/java/com/vayunmathur/health/domain/FhirRecords.ktindex d75b7e1fe0..f4caade0cc 100644--- a/health/src/main/java/com/vayunmathur/health/domain/FhirRecords.kt+++ b/health/src/main/java/com/vayunmathur/health/domain/FhirRecords.kt@@ -5,7 +5,6 @@ import com.vayunmathur.health.data.ConditionEntry 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.PregnancyStatus import com.vayunmathur.health.data.SmokingStatus import com.vayunmathur.health.data.VaccinationEntry@@ -78,8 +77,7 @@ object FhirRecords { fun medicationRequestJson( entry: MedicationEntry,- schedule: MedicationSchedule? = null,- ): String = com.vayunmathur.health.domain.medicationRequestJson(entry, schedule)+ ): String = com.vayunmathur.health.domain.medicationRequestJson(entry) /** "Amoxicillin", "500 mg", "Capsule" rendered as one line for `display` and `text`. */ fun fullMedicationName(entry: MedicationEntry): String =@@ -99,7 +97,7 @@ object FhirRecords { fun parseMedicationRequest( data: String, dataSourceId: String,- ): Pair<MedicationEntry, MedicationSchedule?>? =+ ): MedicationEntry? = com.vayunmathur.health.domain.parseMedicationRequest(data, dataSourceId) fun doseEventJson(event: DoseEvent, medication: MedicationEntry): String =
health/src/main/java/com/vayunmathur/health/platform/DoseReceiver.kt
diff --git a/health/src/main/java/com/vayunmathur/health/platform/DoseReceiver.kt b/health/src/main/java/com/vayunmathur/health/platform/DoseReceiver.ktindex 9bdff1e13b..d439c873e1 100644--- a/health/src/main/java/com/vayunmathur/health/platform/DoseReceiver.kt+++ b/health/src/main/java/com/vayunmathur/health/platform/DoseReceiver.kt@@ -46,8 +46,8 @@ class DoseReceiver : BroadcastReceiver() { DoseNotification.post(context, scheduleId, medicationId, name) // Re-arm before anything else can fail. A missed re-arm silently ends the- // schedule, which is far worse than a reminder that fails to make a noise.- repository.getSchedule(scheduleId)?.let { DoseScheduler.arm(context, it) }+ // reminders, which is far worse than a reminder that fails to make a noise.+ DoseScheduler.arm(context, medication) startSound(context, scheduleId, medicationId, name) } catch (e: Exception) {
health/src/main/java/com/vayunmathur/health/platform/DoseScheduler.kt
diff --git a/health/src/main/java/com/vayunmathur/health/platform/DoseScheduler.kt b/health/src/main/java/com/vayunmathur/health/platform/DoseScheduler.ktindex bde9a6a2d6..afb8be2821 100644--- a/health/src/main/java/com/vayunmathur/health/platform/DoseScheduler.kt+++ b/health/src/main/java/com/vayunmathur/health/platform/DoseScheduler.kt@@ -5,16 +5,17 @@ import android.app.PendingIntent import android.content.Context import android.content.Intent import com.vayunmathur.library.log.Log-import com.vayunmathur.health.data.MedicationSchedule+import com.vayunmathur.health.data.MedicationEntry import com.vayunmathur.health.domain.DoseSchedule import kotlin.time.Clock /**- * Arms and cancels the next dose alarm for a schedule.+ * Arms and cancels the next dose alarm for a medication. *- * Only ever one alarm per schedule, holding the *next* dose and re-armed each time it fires — the+ * Only ever one alarm per medication, holding the *next* dose and re-armed each time it fires — the * clock app's arrangement, which keeps the number of live alarms proportional to the number of- * schedules rather than the number of doses.+ * medications rather than the number of doses. The alarm is derived entirely from the medication+ * record: its dosage timing, its planned end date and its reminder toggle. * * Uses `setAndAllowWhileIdle` rather than the clock's `setAlarmClock`. Precision is not needed here, * and that choice buys a lot: no `SCHEDULE_EXACT_ALARM` or `USE_EXACT_ALARM` permission, no@@ -29,10 +30,10 @@ object DoseScheduler { private const val TAG = "DoseScheduler" - fun arm(context: Context, schedule: MedicationSchedule) {- val next = DoseSchedule.nextDose(schedule, Clock.System.now())+ fun arm(context: Context, medication: MedicationEntry) {+ val next = DoseSchedule.nextDose(medication, Clock.System.now()) if (next == null) {- cancel(context, schedule.id)+ cancel(context, medication.id) return } @@ -40,12 +41,12 @@ object DoseScheduler { alarmManager.setAndAllowWhileIdle( AlarmManager.RTC_WAKEUP, next.toEpochMilliseconds(),- pendingIntent(context, schedule.id, schedule.medicationId, PendingIntent.FLAG_UPDATE_CURRENT),+ pendingIntent(context, medication.id, medication.id, PendingIntent.FLAG_UPDATE_CURRENT), )- Log.status(TAG, "Schedule ${schedule.id}: next dose at $next")+ Log.status(TAG, "Medication ${medication.id}: next dose at $next") } - /** Arms an alarm [delayMillis] from now for a snoozed dose, leaving the schedule alone. */+ /** Arms an alarm [delayMillis] from now for a snoozed dose, leaving the timing alone. */ fun armSnooze(context: Context, scheduleId: String, medicationId: String, delayMillis: Long) { val alarmManager = context.getSystemService(AlarmManager::class.java) ?: return alarmManager.setAndAllowWhileIdle(@@ -57,7 +58,7 @@ object DoseScheduler { fun cancel(context: Context, scheduleId: String) { val alarmManager = context.getSystemService(AlarmManager::class.java) ?: return- // FLAG_NO_CREATE so a schedule that was never armed does not get an alarm conjured for it+ // FLAG_NO_CREATE so a medication that was never armed does not get an alarm conjured for it // just to cancel it. val existing = PendingIntent.getBroadcast( context,
health/src/main/java/com/vayunmathur/health/platform/HealthBootReceiver.kt
diff --git a/health/src/main/java/com/vayunmathur/health/platform/HealthBootReceiver.kt b/health/src/main/java/com/vayunmathur/health/platform/HealthBootReceiver.ktindex 88e4e9ed77..04506ed622 100644--- a/health/src/main/java/com/vayunmathur/health/platform/HealthBootReceiver.kt+++ b/health/src/main/java/com/vayunmathur/health/platform/HealthBootReceiver.kt@@ -11,7 +11,7 @@ import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.launch /**- * Re-arms every enabled dose schedule after a reboot or a time change.+ * Re-arms every medication whose reminder toggle is on after a reboot or a time change. * * `ACTION_BOOT_COMPLETED` only, unlike the clock's equivalent which also handles * `ACTION_LOCKED_BOOT_COMPLETED`. `ClockRepository` is built with `useDeviceProtectedStorage = true`@@ -41,11 +41,11 @@ class HealthBootReceiver : BroadcastReceiver() { val pendingResult = goAsync() CoroutineScope(SupervisorJob() + Dispatchers.IO).launch { try {- val schedules = repository.getEnabledSchedules()- schedules.forEach { DoseScheduler.arm(context, it) }- Log.status(TAG, "$action: re-armed ${schedules.size} schedule(s)")+ val medications = repository.getReminderMedications()+ medications.forEach { DoseScheduler.arm(context, it) }+ Log.status(TAG, "$action: re-armed ${medications.size} medication reminder(s)") } catch (e: Exception) {- Log.error(TAG, "$action: could not re-arm dose schedules", e)+ Log.error(TAG, "$action: could not re-arm dose reminders", e) } finally { pendingResult.finish() }
health/src/main/java/com/vayunmathur/health/platform/MedicalImportOps.kt
diff --git a/health/src/main/java/com/vayunmathur/health/platform/MedicalImportOps.kt b/health/src/main/java/com/vayunmathur/health/platform/MedicalImportOps.ktindex 290f755170..8c3f2bce4d 100644--- a/health/src/main/java/com/vayunmathur/health/platform/MedicalImportOps.kt+++ b/health/src/main/java/com/vayunmathur/health/platform/MedicalImportOps.kt@@ -5,7 +5,6 @@ import androidx.lifecycle.viewModelScope import com.vayunmathur.health.data.HealthProfile import com.vayunmathur.health.data.MedicalKind import com.vayunmathur.health.data.MedicationEntry-import com.vayunmathur.health.data.MedicationSchedule import com.vayunmathur.health.data.MedicationStatus import com.vayunmathur.health.data.PregnancyStatus import com.vayunmathur.health.data.ProfileAnswer@@ -175,7 +174,6 @@ private suspend fun MedicalViewModel.importVaccinesAndMeds(own: String?) { parse = { resource -> FhirRecords.parseMedicationRequest(resource.data, resource.dataSourceId) ?: FhirRecords.parseMedicationStatement(resource.data, resource.dataSourceId)- ?.let { it to null } }, retract = { row -> repository.deleteMedicationEverywhere(getApplication(), row) }, store = { incoming, rowId, existing -> storeMedication(incoming, rowId, existing) },@@ -201,16 +199,25 @@ private suspend fun MedicalViewModel.importVaccinesAndMeds(own: String?) { } private suspend fun MedicalViewModel.storeMedication(- incoming: Pair<MedicationEntry, MedicationSchedule?>,+ incoming: MedicationEntry, rowId: String, existing: MedicationEntry?, ) {- val (entry, schedule) = incoming- repository.upsertMedication(entry.copy(id = rowId))- if (existing == null) {- // An imported schedule arrives disabled, so this cannot start alarms on its own.- schedule?.let { repository.upsertSchedule(it.copy(id = rowId, medicationId = rowId)) }- } else if (entry.status != MedicationStatus.Active) {+ // An imported timing arrives with remindersEnabled = false (see+ // parseMedicationRequest), so this cannot start alarms on its own. For an+ // existing row, keep the user's own toggle/planned end unless the+ // provider has stopped the medication.+ val merged = if (existing == null) {+ incoming.copy(id = rowId)+ } else {+ incoming.copy(+ id = rowId,+ remindersEnabled = existing.remindersEnabled,+ plannedEndDate = existing.plannedEndDate ?: incoming.plannedEndDate,+ )+ }+ repository.upsertMedication(merged)+ if (existing != null && merged.status != MedicationStatus.Active) { // The provider has stopped it, so whatever reminders the user turned on should stop too. repository.disableReminders(getApplication(), rowId) }
health/src/main/java/com/vayunmathur/health/platform/MedicalMedicationOps.kt
diff --git a/health/src/main/java/com/vayunmathur/health/platform/MedicalMedicationOps.kt b/health/src/main/java/com/vayunmathur/health/platform/MedicalMedicationOps.ktindex d1f2ba1f2b..440fab4fa1 100644--- a/health/src/main/java/com/vayunmathur/health/platform/MedicalMedicationOps.kt+++ b/health/src/main/java/com/vayunmathur/health/platform/MedicalMedicationOps.kt@@ -5,7 +5,6 @@ import androidx.lifecycle.viewModelScope import com.vayunmathur.health.data.DoseEvent import com.vayunmathur.health.data.MedicalKind import com.vayunmathur.health.data.MedicationEntry-import com.vayunmathur.health.data.MedicationSchedule import com.vayunmathur.health.data.MedicationStatus import kotlinx.coroutines.launch import java.time.Instant@@ -37,48 +36,37 @@ fun MedicalViewModel.saveMedicationDraft() { // The end field is hidden while Active, so a date left over from before would // otherwise be saved without the user seeing it. endedAt = if (active) null else draft.endedOn?.toInstant(),+ // The planned end date is shown only while Taking; clear it+ // when the course is finished/stopped so no hidden date drives+ // reminders later.+ plannedEndDate = if (active) draft.plannedEndDate else null,+ // Dosage timing lives on the medication record itself.+ doseTimes = draft.times.sorted(),+ repeatUnit = draft.repeatUnit,+ doseInterval = draft.interval.coerceAtLeast(1),+ daysOfWeek = draft.daysOfWeek,+ scheduleAnchorDate = draft.anchorDate,+ // Reminders are literally just this toggle: on means fire per+ // the timing above until plannedEndDate; a course that is no+ // longer being taken never keeps reminders on.+ remindersEnabled = draft.remindersEnabled && active && draft.times.isNotEmpty(), dosageText = draft.dosage.blankToNull(), note = draft.note.blankToNull(), ) val entry = if (detached) edited.copy(fhirResourceId = null, dataSourceId = null) else edited repository.upsertMedication(entry)- saveSchedule(draft, entry.id)+ // Re-arm (or cancel) from the stored row, so what fires is what was saved.+ val context: Context = getApplication()+ if (entry.remindersActive) {+ DoseScheduler.arm(context, entry)+ } else {+ DoseScheduler.cancel(context, entry.id)+ } repository.markPending(MedicalKind.Medication, entry.id) repository.mirrorMedication(entry.id) } } -/**- * Writes or clears the reminder schedule for [medicationId] and re-arms the alarm.- *- * Always re-arms from the stored row rather than the draft, so what fires is what was saved. A- * medication that is no longer being taken keeps its schedule but switched off, so it stops ringing.- */-private suspend fun MedicalViewModel.saveSchedule(- draft: MedicalViewModel.MedicationDraft,- medicationId: String,-) {- val context: Context = getApplication()- if (!draft.remindersEnabled || draft.times.isEmpty()) {- draft.scheduleId?.let { DoseScheduler.cancel(context, it) }- repository.deleteScheduleFor(medicationId)- return- }- val schedule = MedicationSchedule(- id = draft.scheduleId ?: Uuid.random().toString(),- medicationId = medicationId,- enabled = draft.status == MedicationStatus.Active,- times = draft.times.sorted(),- repeatUnit = draft.repeatUnit,- interval = draft.interval.coerceAtLeast(1),- daysOfWeek = draft.daysOfWeek,- anchorDate = draft.anchorDate,- endDate = draft.remindersUntil,- )- repository.upsertSchedule(schedule)- DoseScheduler.arm(context, schedule)-}- fun MedicalViewModel.deleteMedication(entry: MedicationEntry) { viewModelScope.launch { repository.deleteMedicationEverywhere(getApplication(), entry)
health/src/main/java/com/vayunmathur/health/platform/MedicalMirror.kt
diff --git a/health/src/main/java/com/vayunmathur/health/platform/MedicalMirror.kt b/health/src/main/java/com/vayunmathur/health/platform/MedicalMirror.ktindex b6e4429a8d..c412777f55 100644--- a/health/src/main/java/com/vayunmathur/health/platform/MedicalMirror.kt+++ b/health/src/main/java/com/vayunmathur/health/platform/MedicalMirror.kt@@ -94,8 +94,9 @@ internal suspend fun HealthRepository.mirrorTarget( /** * 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.+ * The dosage timing on the entry goes with it, which is what puts the dose+ * times in the record as `dosageInstruction.timing.repeat` rather than leaving+ * them as a private detail of this app. */ internal suspend fun HealthRepository.mirrorMedication(id: String): Boolean { val entry = getMedication(id) ?: run {@@ -105,7 +106,7 @@ internal suspend fun HealthRepository.mirrorMedication(id: String): Boolean { val target = mirrorTarget(MedicalKind.Medication, id, entry.dataSourceId) ?: return false val written = PersonalHealthRecords.upsert( target,- FhirRecords.medicationRequestJson(entry, getScheduleFor(id)),+ FhirRecords.medicationRequestJson(entry), ) ?: return false upsertMedication(entry.copy(fhirResourceId = written, dataSourceId = target)) clearPending(MedicalKind.Medication, id)@@ -158,14 +159,13 @@ internal suspend fun HealthRepository.recordDose(medicationId: String, takenAt: } /**- * Deletes a medication with its schedule and doses, here and in Health Connect.+ * Deletes a medication with its doses, here and in Health Connect. * * The doses go with it. Leaving them would strand statements pointing at a MedicationRequest that * no longer exists, and the next import would read them back as orphan rows. */ internal suspend fun HealthRepository.deleteMedicationEverywhere(context: Context, entry: MedicationEntry) {- getScheduleFor(entry.id)?.let { DoseScheduler.cancel(context, it.id) }- deleteScheduleFor(entry.id)+ DoseScheduler.cancel(context, entry.id) val doses = getDosesFor(entry.id) deleteDosesFor(entry.id) deleteMedication(entry)@@ -187,9 +187,9 @@ internal suspend fun HealthRepository.deleteMedicationEverywhere(context: Contex ) } -/** Turns a medication's reminders off without discarding the schedule itself. */+/** Turns a medication's reminder toggle off without discarding its dosage timing. */ internal suspend fun HealthRepository.disableReminders(context: Context, medicationId: String) {- val schedule = getScheduleFor(medicationId) ?: return- DoseScheduler.cancel(context, schedule.id)- if (schedule.enabled) upsertSchedule(schedule.copy(enabled = false))+ DoseScheduler.cancel(context, medicationId)+ val medication = getMedication(medicationId) ?: return+ if (medication.remindersEnabled) upsertMedication(medication.copy(remindersEnabled = false)) }
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 0457e01def..b44a9cb479 100644--- a/health/src/main/java/com/vayunmathur/health/platform/MedicalViewModel.kt+++ b/health/src/main/java/com/vayunmathur/health/platform/MedicalViewModel.kt@@ -18,7 +18,6 @@ import com.vayunmathur.health.data.HealthRepository import com.vayunmathur.health.data.LabResultEntry import com.vayunmathur.health.data.MedicalAttachment 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@@ -116,12 +115,6 @@ class MedicalViewModel( .map { all -> all.groupBy { it.vaccinationId } } .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyMap()) - /** Reminder schedules keyed by the medication they belong to. */- val schedules: StateFlow<Map<String, MedicationSchedule>> =- repository.getSchedulesFlow()- .map { all -> all.associateBy { it.medicationId } }- .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyMap())- /** Every dose taken, newest first. */ val doseEvents: StateFlow<List<DoseEvent>> = repository.getDoseEventsFlow() .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())@@ -193,16 +186,17 @@ class MedicalViewModel( val endedOn: LocalDate? = null, val dosage: String = "", val note: String = "",- // --- Reminder schedule ---- val scheduleId: String? = null,- val remindersEnabled: Boolean = false,+ /** Optional planned last day, shown only while the status is Taking. */+ val plannedEndDate: LocalDate? = null,+ // --- Dosage timing (on the medication record itself) --- /** Seconds since midnight, one per dose. */ val times: List<Int> = listOf(DEFAULT_DOSE_TIME_SECONDS), val repeatUnit: RepeatUnit = RepeatUnit.Daily, val interval: Int = 1, val daysOfWeek: Int = 0, val anchorDate: LocalDate = today(),- val remindersUntil: LocalDate? = null,+ // --- Reminders: literally just this toggle ---+ val remindersEnabled: Boolean = false, /** * Which entry in [times] the time picker is currently editing, or [times].size to append. *@@ -366,7 +360,6 @@ class MedicalViewModel( if (id == null) return viewModelScope.launch { val entry = repository.getMedication(id) ?: return@launch- val schedule = repository.getScheduleFor(id) medicationDraftState.value = MedicationDraft( editingId = entry.id, rxcui = entry.rxcui,@@ -378,23 +371,22 @@ class MedicalViewModel( endedOn = entry.endedAt?.toLocalDate(), dosage = entry.dosageText.orEmpty(), note = entry.note.orEmpty(),- scheduleId = schedule?.id,- // A stopped medication's schedule is kept but switched off; showing it as on is- // what lets reactivating the medication bring its reminders back.- remindersEnabled = schedule != null &&- (schedule.enabled || entry.status != MedicationStatus.Active),+ plannedEndDate = entry.plannedEndDate,+ // Show the toggle as the user left it even for a stopped+ // medication, so reactivating it can bring reminders back;+ // saving forces it off while not Taking.+ remindersEnabled = entry.remindersEnabled, // Drop out-of-range dose times stored by older imports: the // editor renders each with LocalTime.fromSecondOfDay, which // throws outside 0..86399. DoseSchedule already ignores them // when arming; this keeps the editor consistent with that.- times = schedule?.times?.filter { it in 0 until SECONDS_PER_DAY }- ?.takeIf { it.isNotEmpty() }+ times = entry.doseTimes.filter { it in 0 until SECONDS_PER_DAY }+ .takeIf { it.isNotEmpty() } ?: listOf(DEFAULT_DOSE_TIME_SECONDS),- repeatUnit = schedule?.repeatUnit ?: RepeatUnit.Daily,- interval = schedule?.interval ?: 1,- daysOfWeek = schedule?.daysOfWeek ?: 0,- anchorDate = schedule?.anchorDate ?: today(),- remindersUntil = schedule?.endDate,+ repeatUnit = entry.repeatUnit,+ interval = entry.doseInterval,+ daysOfWeek = entry.daysOfWeek,+ anchorDate = entry.scheduleAnchorDate ?: entry.startedAt.toLocalDate(), ) } }
health/src/main/java/com/vayunmathur/health/ui/AddMedicationPage.kt
diff --git a/health/src/main/java/com/vayunmathur/health/ui/AddMedicationPage.kt b/health/src/main/java/com/vayunmathur/health/ui/AddMedicationPage.ktindex 668f84ab59..7a5d780ac8 100644--- a/health/src/main/java/com/vayunmathur/health/ui/AddMedicationPage.kt+++ b/health/src/main/java/com/vayunmathur/health/ui/AddMedicationPage.kt@@ -10,7 +10,8 @@ import com.vayunmathur.health.data.MedicationStatus import com.vayunmathur.health.platform.MedicalViewModel import com.vayunmathur.health.platform.saveMedicationDraft import com.vayunmathur.health.ui.components.PickerField-import com.vayunmathur.health.ui.components.ScheduleSection+import com.vayunmathur.health.ui.components.DosageTimingSection+import com.vayunmathur.health.ui.components.ReminderToggleSection import com.vayunmathur.library.ui.DetailScaffold import com.vayunmathur.library.ui.ExperimentalMaterial3Api import com.vayunmathur.library.ui.FormSection@@ -28,7 +29,7 @@ import kotlinx.datetime.LocalTime private const val START_KEY = "add-medication/start" private const val END_KEY = "add-medication/end" private const val TIME_KEY = "add-medication/time"-private const val UNTIL_KEY = "add-medication/until"+private const val PLANNED_END_KEY = "add-medication/planned-end" /** * The form for adding or editing a medication.@@ -52,8 +53,8 @@ fun AddMedicationPage(backStack: NavBackStack<Route>, viewModel: MedicalViewMode ResultEffect<DateSelection>(END_KEY) { picked -> viewModel.editMedicationDraft { it.copy(endedOn = picked.date) } }- ResultEffect<DateSelection>(UNTIL_KEY) { picked ->- viewModel.editMedicationDraft { it.copy(remindersUntil = picked.date) }+ ResultEffect<DateSelection>(PLANNED_END_KEY) { picked ->+ viewModel.editMedicationDraft { it.copy(plannedEndDate = picked.date) } } // One picker route serves every dose row, so which row it was opened for is carried in the // draft — this screen is not composed while the dialog is up.@@ -125,6 +126,25 @@ fun AddMedicationPage(backStack: NavBackStack<Route>, viewModel: MedicalViewMode placeholder = "", onClick = { backStack.add(Route.MedicalDatePicker(START_KEY, draft.startedOn)) }, )+ if (draft.status == MedicationStatus.Active) {+ PickerField(+ label = stringResource(R.string.field_planned_end),+ value = draft.plannedEndDate?.let { medicalDateString(it.toInstant()) }.orEmpty(),+ placeholder = stringResource(R.string.no_end_date),+ onClick = {+ backStack.add(+ Route.MedicalDatePicker(+ PLANNED_END_KEY,+ draft.plannedEndDate ?: draft.startedOn,+ allowClear = true,+ )+ )+ },+ onClear = {+ viewModel.editMedicationDraft { it.copy(plannedEndDate = null) }+ },+ )+ } if (draft.status != MedicationStatus.Active) { PickerField( label = stringResource(R.string.field_ended),@@ -157,8 +177,8 @@ fun AddMedicationPage(backStack: NavBackStack<Route>, viewModel: MedicalViewMode ) } - FormSection(title = stringResource(R.string.section_reminders)) {- ScheduleSection(+ FormSection(title = stringResource(R.string.section_dosage_timing)) {+ DosageTimingSection( draft = draft, onEdit = { transform -> viewModel.editMedicationDraft(transform) }, onPickTime = { index ->@@ -167,15 +187,13 @@ fun AddMedicationPage(backStack: NavBackStack<Route>, viewModel: MedicalViewMode Route.MedicalTimePicker(TIME_KEY, LocalTime(9, 0)) ) },- onPickUntil = {- backStack.add(- Route.MedicalDatePicker(- UNTIL_KEY,- draft.remindersUntil ?: draft.startedOn,- allowClear = true,- )- )- },+ )+ }++ FormSection(title = stringResource(R.string.section_reminders)) {+ ReminderToggleSection(+ draft = draft,+ onEdit = { transform -> viewModel.editMedicationDraft(transform) }, ) } }
health/src/main/java/com/vayunmathur/health/ui/components/DosageTimingSection.kt
diff --git a/health/src/main/java/com/vayunmathur/health/ui/components/ScheduleSection.kt b/health/src/main/java/com/vayunmathur/health/ui/components/DosageTimingSection.ktsimilarity index 61%rename from health/src/main/java/com/vayunmathur/health/ui/components/ScheduleSection.ktrename to health/src/main/java/com/vayunmathur/health/ui/components/DosageTimingSection.ktindex 73445adc4d..4103ada2fd 100644--- a/health/src/main/java/com/vayunmathur/health/ui/components/ScheduleSection.kt+++ b/health/src/main/java/com/vayunmathur/health/ui/components/DosageTimingSection.kt@@ -1,97 +1,46 @@ package com.vayunmathur.health.ui.components -import android.app.NotificationManager-import android.content.Intent-import android.os.Build-import android.provider.Settings import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable-import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier-import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp-import androidx.core.net.toUri import com.vayunmathur.health.R import com.vayunmathur.health.data.RepeatUnit import com.vayunmathur.health.platform.MedicalViewModel-import com.vayunmathur.health.ui.medicalDateString-import com.vayunmathur.health.ui.toInstant-import com.vayunmathur.library.ui.Card import com.vayunmathur.library.ui.DateString import com.vayunmathur.library.ui.ExperimentalMaterial3Api import com.vayunmathur.library.ui.LabeledTextField-import com.vayunmathur.library.ui.ListItem import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.MultiCategoryPicker import com.vayunmathur.library.ui.SettingsExposedSelectRow-import com.vayunmathur.library.ui.Switch import com.vayunmathur.library.ui.Text-import com.vayunmathur.library.ui.TextButton import com.vayunmathur.library.ui.ToggleButton import com.vayunmathur.library.ui.rememberIs24Hour import kotlinx.datetime.LocalTime /**- * The reminder schedule, edited inline on the medication form.+ * The dosage timing, edited inline on the medication form.+ *+ * This timing belongs to the medication record itself, not to its reminders:+ * reminders are just a toggle elsewhere on the form and fire per this timing+ * until the medication's planned end date. * * Everything here writes straight into the ViewModel draft rather than into `remember`, because the * form is disposed whenever a picker opens over it. */ @OptIn(ExperimentalMaterial3Api::class) @Composable-fun ScheduleSection(+fun DosageTimingSection( draft: MedicalViewModel.MedicationDraft, onEdit: ((MedicalViewModel.MedicationDraft) -> MedicalViewModel.MedicationDraft) -> Unit, onPickTime: (index: Int) -> Unit,- onPickUntil: () -> Unit, modifier: Modifier = Modifier, ) {- val context = LocalContext.current-- Row(- modifier = modifier.fillMaxWidth(),- verticalAlignment = Alignment.CenterVertically,- horizontalArrangement = Arrangement.SpaceBetween,- ) {- Text(stringResource(R.string.remind_me))- Switch(- checked = draft.remindersEnabled,- onCheckedChange = { on -> onEdit { it.copy(remindersEnabled = on) } },- )- }-- if (!draft.remindersEnabled) return-- // On Android 14+ this is auto-granted only to calling and alarm apps, so a health app starts- // without it and the reminder would quietly be a heads-up notification instead of a takeover.- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {- val manager = context.getSystemService(NotificationManager::class.java)- if (manager != null && !manager.canUseFullScreenIntent()) {- Card(modifier = Modifier.fillMaxWidth()) {- ListItem(- headlineContent = { Text(stringResource(R.string.full_screen_intent_needed)) },- trailingContent = {- TextButton(- onClick = {- context.startActivity(- Intent(- Settings.ACTION_MANAGE_APP_USE_FULL_SCREEN_INTENT,- "package:${context.packageName}".toUri(),- )- )- }- ) { Text(stringResource(R.string.grant_full_screen)) }- },- )- }- }- }- // Chips in a field, the same control the contacts app uses for categories — except that tapping // it opens the time picker rather than a menu, since a time of day does not come from a fixed // list. Tapping a chip removes that time.@@ -102,13 +51,13 @@ fun ScheduleSection( itemLabel = { seconds -> DateString.time(LocalTime.fromSecondOfDay(seconds), is24Hour) }, onAddClick = { onPickTime(draft.times.size) }, onRemove = { seconds ->- // Never let the last one go: a schedule with no times can never fire, and an empty+ // Never let the last one go: a timing with no times can never fire, and an empty // field would read as a bug rather than a choice. if (draft.times.size > 1) { onEdit { d -> d.copy(times = d.times - seconds) } } },- modifier = Modifier.padding(top = 8.dp),+ modifier = modifier.padding(top = 8.dp), ) val unitLabels = mapOf(@@ -164,11 +113,4 @@ fun ScheduleSection( } } }-- PickerField(- label = stringResource(R.string.reminders_until),- value = draft.remindersUntil?.let { medicalDateString(it.toInstant()) }.orEmpty(),- placeholder = stringResource(R.string.no_end_date),- onClick = onPickUntil,- ) }
health/src/main/java/com/vayunmathur/health/ui/components/PickerField.kt
diff --git a/health/src/main/java/com/vayunmathur/health/ui/components/PickerField.kt b/health/src/main/java/com/vayunmathur/health/ui/components/PickerField.ktindex 93d334519f..d4b8faa5e7 100644--- a/health/src/main/java/com/vayunmathur/health/ui/components/PickerField.kt+++ b/health/src/main/java/com/vayunmathur/health/ui/components/PickerField.kt@@ -4,7 +4,9 @@ import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier+import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.IconChevronRight+import com.vayunmathur.library.ui.IconClose import com.vayunmathur.library.ui.ListItem import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.OutlinedCard@@ -27,6 +29,7 @@ fun PickerField( onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true,+ onClear: (() -> Unit)? = null, ) { OutlinedCard( modifier = modifier.fillMaxWidth().clickable(enabled = enabled, onClick = onClick),@@ -40,7 +43,13 @@ fun PickerField( Text(placeholder, color = MaterialTheme.colorScheme.onSurfaceVariant) } },- trailingContent = { IconChevronRight() },+ trailingContent = {+ if (enabled && onClear != null && value.isNotBlank()) {+ IconButton(onClick = onClear) { IconClose() }+ } else {+ IconChevronRight()+ }+ }, ) } }
health/src/main/java/com/vayunmathur/health/ui/components/ReminderToggleSection.kt
diff --git a/health/src/main/java/com/vayunmathur/health/ui/components/ReminderToggleSection.kt b/health/src/main/java/com/vayunmathur/health/ui/components/ReminderToggleSection.ktnew file mode 100644index 0000000000..9e78d1f9f6--- /dev/null+++ b/health/src/main/java/com/vayunmathur/health/ui/components/ReminderToggleSection.kt@@ -0,0 +1,77 @@+package com.vayunmathur.health.ui.components++import android.app.NotificationManager+import android.content.Intent+import android.os.Build+import android.provider.Settings+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.core.net.toUri+import com.vayunmathur.health.R+import com.vayunmathur.health.platform.MedicalViewModel+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.Switch+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton++/**+ * The reminder toggle on the medication form.+ *+ * Literally just a toggle: when on, reminders fire per the medication's own+ * dosage timing and stop after its planned end date. There is no reminder+ * schedule or reminder end date to edit here.+ */+@Composable+fun ReminderToggleSection(+ draft: MedicalViewModel.MedicationDraft,+ onEdit: ((MedicalViewModel.MedicationDraft) -> MedicalViewModel.MedicationDraft) -> Unit,+ modifier: Modifier = Modifier,+) {+ val context = LocalContext.current++ Row(+ modifier = modifier.fillMaxWidth(),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.SpaceBetween,+ ) {+ Text(stringResource(R.string.remind_me))+ Switch(+ checked = draft.remindersEnabled,+ onCheckedChange = { on -> onEdit { it.copy(remindersEnabled = on) } },+ )+ }++ if (!draft.remindersEnabled) return++ // On Android 14+ this is auto-granted only to calling and alarm apps, so a health app starts+ // without it and the reminder would quietly be a heads-up notification instead of a takeover.+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {+ val manager = context.getSystemService(NotificationManager::class.java)+ if (manager !
Diff truncated.