health: import lab results from PDF via OpenAssistant
- Commit
26b2d97d1171f522336e3ca55eb74913851fb27d- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-05 14:44 UTC (19 hours ago)
- Parents
dfba320
Medical tab gains Import lab PDF (OpenDocument, PDF only). The PDF is copied to app-private files/lab_documents (LabDocumentStore; carried by AppBackupAgent like medical_attachments, so it survives backup), rendered page-by-page health-locally with the platform PdfRenderer (LabPdfRenderer: the Rust engine lives in the :pdf app and cannot be depended on, and no new dependency was added), and each page image is sent to OpenAssistant through the SDK vision structured call with the domain/LabExtraction schema. Parsing is non-throwing with provider-side clamping (blank names rejected, lengths capped, inverted ranges dropped, bad dates nulled); per-page failures are collected and reported, a total failure deletes the stored PDF and writes nothing, and a missing/unavailable model surfaces as an error with no writes. Nothing is written before the new Route.LabImportReview confirmation screen, which marks tests not in the catalogue as New test and lets rows be removed. Confirm (confirmLabImport, the only writer) inserts the LabDocument (DB v14, migration 13-14), writes LabResultEntry rows alongside manual ones with sourceDocumentId + 1-based sourcePage + panel, marks them pending Health Connect mirror like manual saves, dedupes on normalized test+date+value against existing rows, and creates LabTestCatalogEntry rows for unmatched tests. The lab result form shows the source PDF with View (ACTION_VIEW via FileProvider, opens the pdf viewer) and Delete PDF; deleting keeps the results and their link then honestly reports the document as gone. The manual test chooser also now actually lists tests: it previously returned nothing for a blank query and the bundled LOINC table is often empty, so it looked empty. CatalogKind.LabTest now merges recorded tests (with their known unit/range), custom catalogue entries and bundled LOINC names/units (ReferenceCatalog.browseLabs; no reference ranges are invented, LOINC has none in this app), filters by normalized substring, and picking pre-fills unit/reference range into empty fields; typed names are saved as custom catalogue entries. Extraction matches onto this same catalogue by normalized name. Tests: LabExtractionTest (parse/clamp/malformed/dedupe key), LabCatalogTest (blank picker, filtering, matcher, merge precedence), LabImportOpsTest (confirmation gate writes nothing before confirm, linkage document+page, re-import dedupe), updated MigrationsTest (chain to v14) and HealthBackupAgentTest (lab_documents carried). Verified :health:lint, :health:lintVitalRelease green; :health:testDevUnitTest passes except RecipeEditorFlowTest which passes alone and times out only in the full batched suite (its own comment documents that full-suite race; not touched by this change).
Diff
health/AGENTS.md
diff --git a/health/AGENTS.md b/health/AGENTS.mdindex ebd2e7cd0f..033ce6e0d2 100644--- a/health/AGENTS.md+++ b/health/AGENTS.md@@ -16,7 +16,7 @@ _Install: ./install health (dev by default)._ - Per-metric dashboards with charts/history (`GenericLineChart`/`GenericBarChart`, hypnogram for sleep) - 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`, `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).+**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 v14 (migration 13→14 adds `LabDocument`, `LabTestCatalogEntry` and `LabResultEntry.sourceDocumentId/sourcePage/panel`); the medication timing/end/toggle columns live on `MedicationEntry`. Lab PDF import: Medical tab FAB → `MedicalLabImportOps.startLabPdfImport` stores the PDF in `files/lab_documents/` (backed up via `AppBackupAgent`), renders pages health-locally with platform `PdfRenderer` (`LabPdfRenderer`; the Rust engine is :pdf-app-private), extracts per page via `sdk:openassistant` `generateJsonWithImages` + `domain/LabExtraction` schema/clamping, and writes only on confirm in `Route.LabImportReview` (dedupe by normalized test+date+value; unmatched tests become `LabTestCatalogEntry` rows). Deleting a PDF keeps its results, whose source link then reports it gone. The lab-test picker (`CatalogKind.LabTest`) lists a merged catalogue — recorded tests, custom catalogue rows, bundled LOINC names/units from `ReferenceCatalog` (no invented reference ranges) — and pre-fills unit/range where known. **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).
health/build.gradle.kts
diff --git a/health/build.gradle.kts b/health/build.gradle.ktsindex 6d86673d31..f613cdb54a 100644--- a/health/build.gradle.kts+++ b/health/build.gradle.kts@@ -33,6 +33,7 @@ dependencies { // room implementRoom(libs) implementation(project(":library:room"))+ implementation(project(":sdk:openassistant")) // Decodes the brotli-compressed food database asset. This is the only // reason the app links a codec at all; it does not use the network.
health/schemas/com.vayunmathur.health.data.HealthDatabase/14.json
diff --git a/health/schemas/com.vayunmathur.health.data.HealthDatabase/14.json b/health/schemas/com.vayunmathur.health.data.HealthDatabase/14.jsonnew file mode 100644index 0000000000..bdc8fb0454--- /dev/null+++ b/health/schemas/com.vayunmathur.health.data.HealthDatabase/14.json@@ -0,0 +1,1731 @@+{+ "formatVersion": 1,+ "database": {+ "version": 14,+ "identityHash": "f323c548bebf092ba1cad13a23fbd80b",+ "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, `sourceDocumentId` TEXT, `sourcePage` INTEGER, `panel` 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"+ },+ {+ "fieldPath": "sourceDocumentId",+ "columnName": "sourceDocumentId",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "sourcePage",+ "columnName": "sourcePage",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "panel",+ "columnName": "panel",+ "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"+ ]+ }+ },+ {+ "tableName": "LabDocument",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `fileName` TEXT NOT NULL, `displayName` TEXT NOT NULL, `mimeType` TEXT NOT NULL, `sizeBytes` INTEGER NOT NULL, `pageCount` INTEGER NOT NULL, `importedAt` INTEGER NOT NULL, PRIMARY KEY(`id`))",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "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": "pageCount",+ "columnName": "pageCount",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "importedAt",+ "columnName": "importedAt",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_LabDocument_importedAt",+ "unique": false,+ "columnNames": [+ "importedAt"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_LabDocument_importedAt` ON `${TABLE_NAME}` (`importedAt`)"+ }+ ]+ },+ {+ "tableName": "LabTestCatalogEntry",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `loincCode` TEXT, `displayName` TEXT NOT NULL, `unit` TEXT, `referenceLow` REAL, `referenceHigh` REAL, `panel` 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": "unit",+ "columnName": "unit",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "referenceLow",+ "columnName": "referenceLow",+ "affinity": "REAL"+ },+ {+ "fieldPath": "referenceHigh",+ "columnName": "referenceHigh",+ "affinity": "REAL"+ },+ {+ "fieldPath": "panel",+ "columnName": "panel",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_LabTestCatalogEntry_displayName",+ "unique": false,+ "columnNames": [+ "displayName"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_LabTestCatalogEntry_displayName` ON `${TABLE_NAME}` (`displayName`)"+ }+ ]+ }+ ],+ "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, 'f323c548bebf092ba1cad13a23fbd80b')"+ ]+ }+}\ No newline at end of file
health/src/main/java/com/vayunmathur/health/Route.kt
diff --git a/health/src/main/java/com/vayunmathur/health/Route.kt b/health/src/main/java/com/vayunmathur/health/Route.ktindex 5a40fbd630..f662c02fcb 100644--- a/health/src/main/java/com/vayunmathur/health/Route.kt+++ b/health/src/main/java/com/vayunmathur/health/Route.kt@@ -13,6 +13,7 @@ import kotlinx.serialization.Serializable // SCREENSHOT COVERAGE EXCEPTION: EditCondition: form edits a MedicalViewModel draft loaded from Room/Health Connect; no stateless slice for Layoutlib // SCREENSHOT COVERAGE EXCEPTION: EditLabResult: form edits a MedicalViewModel draft loaded from Room/Health Connect; no stateless slice for Layoutlib // SCREENSHOT COVERAGE EXCEPTION: CatalogPicker: picker searches MedicalViewModel catalog flows (CVX/RxNorm/LOINC) and writes the draft; no stateless slice for Layoutlib+// SCREENSHOT COVERAGE EXCEPTION: LabImportReview: review reads MedicalViewModel PDF-import state; no stateless slice for Layoutlib // SCREENSHOT COVERAGE EXCEPTION: LogMealDialog: dialog lists ViewModel recipe/ingredient flows and logs through the ViewModel; no stateless slice for Layoutlib // SCREENSHOT COVERAGE EXCEPTION: AddIngredientDialog: dialog searches the bundled food database and remote API through the ViewModel; no stateless slice for Layoutlib /** Contract for route. */@@ -78,6 +79,10 @@ sealed interface Route: NavKey { @Serializable data class EditLabResult(val id: String? = null): Route + /** Review of PDF-extracted lab results; nothing is written until confirmed there. */+ @Serializable+ data object LabImportReview: Route+ /** * The searchable reference-data picker. [ingredient] narrows * [com.vayunmathur.health.ui.CatalogKind.MedicationProduct] to one drug and is unused otherwise.
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 b906522ed7..e05ea0783e 100644--- a/health/src/main/java/com/vayunmathur/health/data/HealthRepository.kt+++ b/health/src/main/java/com/vayunmathur/health/data/HealthRepository.kt@@ -206,6 +206,15 @@ class HealthRepository private constructor(context: Context) : suspend fun getLabResult(id: String): LabResultEntry? = medicalDao.getLabResult(id) suspend fun findLabResult(dataSourceId: String, fhirResourceId: String): LabResultEntry? = medicalDao.findLabResult(dataSourceId, fhirResourceId)+ suspend fun getLabResultsForDocument(documentId: String): List<LabResultEntry> =+ medicalDao.getLabResultsForDocument(documentId)+ suspend fun upsertLabDocument(document: LabDocument) = medicalDao.upsertLabDocument(document)+ suspend fun deleteLabDocument(document: LabDocument) = medicalDao.deleteLabDocument(document)+ fun getLabDocumentsFlow(): Flow<List<LabDocument>> = medicalDao.getLabDocumentsFlow()+ suspend fun getLabDocument(id: String): LabDocument? = medicalDao.getLabDocument(id)+ suspend fun upsertLabCatalogEntry(entry: LabTestCatalogEntry) = medicalDao.upsertLabCatalogEntry(entry)+ fun getLabCatalogFlow(): Flow<List<LabTestCatalogEntry>> = medicalDao.getLabCatalogFlow()+ suspend fun getLabCatalogEntries(): List<LabTestCatalogEntry> = medicalDao.getLabCatalogEntries() suspend fun upsertProfile(profile: HealthProfile) = medicalDao.upsertProfile(profile) fun getProfileFlow(): Flow<HealthProfile?> = medicalDao.getProfileFlow()
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 fadca3b066..0cc9681a0a 100644--- a/health/src/main/java/com/vayunmathur/health/data/MedicalRecords.kt+++ b/health/src/main/java/com/vayunmathur/health/data/MedicalRecords.kt@@ -169,6 +169,30 @@ enum class SmokingStatus { Unknown, Never, Former, Current } * detected" — so [value] and [valueText] are alternatives rather than both being filled. FHIR models * that the same way, as `valueQuantity` against `valueString`. */+/** A lab-report PDF stored by the app; imported results link back to it. */+@Entity(indices = [Index(value = ["importedAt"])])+data class LabDocument(+ @PrimaryKey val id: String,+ val fileName: String,+ val displayName: String,+ val mimeType: String = "application/pdf",+ val sizeBytes: Long,+ val pageCount: Int,+ val importedAt: Instant,+)++/** A user-created / PDF-proposed lab test catalogue entry (no invented ranges). */+@Entity(indices = [Index(value = ["displayName"])])+data class LabTestCatalogEntry(+ @PrimaryKey val id: String,+ val loincCode: String? = null,+ val displayName: String,+ val unit: String? = null,+ val referenceLow: Double? = null,+ val referenceHigh: Double? = null,+ val panel: String? = null,+)+ @Entity(indices = [Index(value = ["takenAt"])]) data class LabResultEntry( @PrimaryKey val id: String,@@ -186,6 +210,12 @@ data class LabResultEntry( val note: String? = null, val fhirResourceId: String? = null, val dataSourceId: String? = null,+ /** Source PDF document id for PDF imports; null for manual/Health Connect rows. */+ val sourceDocumentId: String? = null,+ /** 1-based page in [sourceDocumentId] this result was extracted from. */+ val sourcePage: Int? = null,+ /** Panel/group heading the test appeared under, when known. */+ val panel: String? = null, ) { /** Whether a numeric result sits outside its own reference range, when it has one. */ val isOutOfRange: Boolean@@ -418,6 +448,32 @@ interface MedicalDao { ) suspend fun findLabResult(dataSourceId: String, fhirResourceId: String): LabResultEntry? + @Query("SELECT * FROM LabResultEntry WHERE sourceDocumentId = :documentId ORDER BY takenAt DESC")+ suspend fun getLabResultsForDocument(documentId: String): List<LabResultEntry>++ // --- Lab documents + catalogue ----------------------------------------++ @Insert(onConflict = OnConflictStrategy.REPLACE)+ suspend fun upsertLabDocument(document: LabDocument)++ @Delete+ suspend fun deleteLabDocument(document: LabDocument)++ @Query("SELECT * FROM LabDocument ORDER BY importedAt DESC")+ fun getLabDocumentsFlow(): Flow<List<LabDocument>>++ @Query("SELECT * FROM LabDocument WHERE id = :id")+ suspend fun getLabDocument(id: String): LabDocument?++ @Insert(onConflict = OnConflictStrategy.REPLACE)+ suspend fun upsertLabCatalogEntry(entry: LabTestCatalogEntry)++ @Query("SELECT * FROM LabTestCatalogEntry ORDER BY displayName ASC")+ fun getLabCatalogFlow(): Flow<List<LabTestCatalogEntry>>++ @Query("SELECT * FROM LabTestCatalogEntry")+ suspend fun getLabCatalogEntries(): List<LabTestCatalogEntry>+ // --- Profile ----------------------------------------------------------- @Insert(onConflict = OnConflictStrategy.REPLACE)
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 834b9e8d1c..ead7ca3fff 100644--- a/health/src/main/java/com/vayunmathur/health/data/Record.kt+++ b/health/src/main/java/com/vayunmathur/health/data/Record.kt@@ -399,11 +399,9 @@ interface HealthDao { /** On-disk name of the [HealthDatabase] file (the [com.vayunmathur.library.room.RoomRepository] default). */ const val DB_NAME = "passwords-db"- /** Backup config shared by [com.vayunmathur.health.platform.AppBackupAgent]. */ fun healthDbConfigs(context: Context): List<Pair<String, String>> = listOf(DB_NAME to DatabaseHelper(context).getPassphrase())- @Database( entities = [ Record::class, Ingredient::class, Recipe::class, ServingUnit::class, RecipeIngredient::class,@@ -411,8 +409,9 @@ fun healthDbConfigs(context: Context): List<Pair<String, String>> = AllergyEntry::class, ConditionEntry::class, LabResultEntry::class, HealthProfile::class, ProfileAnswer::class, DoseEvent::class, DeletedMedicalResource::class, PendingMirror::class,+ LabDocument::class, LabTestCatalogEntry::class, ],- version = 13,+ version = 14, exportSchema = true ) /** Health Database: a room database implementation for health database. */@@ -420,7 +419,6 @@ fun healthDbConfigs(context: Context): List<Pair<String, String>> = abstract class HealthDatabase : RoomDatabase() { abstract fun healthDao(): HealthDao abstract fun medicalDao(): MedicalDao- /** Shared constants and helpers for HealthDatabase. */ companion object : com.vayunmathur.library.util.DatabaseMigrations { override val migrations = listOf(@@ -764,13 +762,7 @@ abstract class HealthDatabase : RoomDatabase() { ) } },- // 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.+ // v12 -> v13: dosage timing/planned end move onto MedicationEntry. Migration(12, 13) { it.execSQL("ALTER TABLE MedicationEntry ADD COLUMN plannedEndDate INTEGER") it.execSQL("ALTER TABLE MedicationEntry ADD COLUMN doseTimes TEXT NOT NULL DEFAULT ''")@@ -790,8 +782,17 @@ abstract class HealthDatabase : RoomDatabase() { "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")+ it.execSQL("DROP INDEX IF EXISTS index_MedicationSchedule_medicationId"); it.execSQL("DROP TABLE IF EXISTS MedicationSchedule")+ },+ // v13 -> v14: lab PDF linkage + lab-test catalogue.+ Migration(13, 14) {+ it.execSQL("ALTER TABLE LabResultEntry ADD COLUMN sourceDocumentId TEXT")+ it.execSQL("ALTER TABLE LabResultEntry ADD COLUMN sourcePage INTEGER")+ it.execSQL("ALTER TABLE LabResultEntry ADD COLUMN panel TEXT")+ it.execSQL("CREATE TABLE IF NOT EXISTS LabDocument (id TEXT NOT NULL PRIMARY KEY, fileName TEXT NOT NULL, displayName TEXT NOT NULL, mimeType TEXT NOT NULL, sizeBytes INTEGER NOT NULL, pageCount INTEGER NOT NULL, importedAt INTEGER NOT NULL)")+ it.execSQL("CREATE INDEX IF NOT EXISTS index_LabDocument_importedAt ON LabDocument (importedAt)")+ it.execSQL("CREATE TABLE IF NOT EXISTS LabTestCatalogEntry (id TEXT NOT NULL PRIMARY KEY, loincCode TEXT, displayName TEXT NOT NULL, unit TEXT, referenceLow REAL, referenceHigh REAL, panel TEXT)")+ it.execSQL("CREATE INDEX IF NOT EXISTS index_LabTestCatalogEntry_displayName ON LabTestCatalogEntry (displayName)") } ) }
health/src/main/java/com/vayunmathur/health/data/ReferenceCatalog.kt
diff --git a/health/src/main/java/com/vayunmathur/health/data/ReferenceCatalog.kt b/health/src/main/java/com/vayunmathur/health/data/ReferenceCatalog.ktindex 1255e0034f..acb4a09f1c 100644--- a/health/src/main/java/com/vayunmathur/health/data/ReferenceCatalog.kt+++ b/health/src/main/java/com/vayunmathur/health/data/ReferenceCatalog.kt@@ -347,6 +347,27 @@ object ReferenceCatalog { } } + /** Common LOINC tests for an empty picker query, ranked as in [searchLabs]. */+ suspend fun browseLabs(limit: Int = 100): List<LabTest> = withContext(Dispatchers.IO) {+ val db = openHandle() ?: return@withContext emptyList()+ try {+ db.rawQuery(+ "SELECT code, name, unit FROM labs ORDER BY (rank = 0), rank ASC, LENGTH(name) ASC LIMIT ?",+ arrayOf(limit.toString()),+ ).use { cursor ->+ buildList {+ while (cursor.moveToNext()) {+ add(LabTest(cursor.getString(0), cursor.getString(1),+ if (cursor.isNull(2)) null else cursor.getString(2)))+ }+ }+ }+ } catch (e: android.database.sqlite.SQLiteException) {+ Log.error(TAG, "Lab browse failed", e)+ emptyList()+ }+ }+ // --- Conditions -------------------------------------------------------- /**
health/src/main/java/com/vayunmathur/health/domain/LabExtraction.kt
diff --git a/health/src/main/java/com/vayunmathur/health/domain/LabExtraction.kt b/health/src/main/java/com/vayunmathur/health/domain/LabExtraction.ktnew file mode 100644index 0000000000..19df13fb25--- /dev/null+++ b/health/src/main/java/com/vayunmathur/health/domain/LabExtraction.kt@@ -0,0 +1,96 @@+package com.vayunmathur.health.domain++import kotlinx.datetime.LocalDate+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.JsonElement+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.JsonPrimitive+import kotlinx.serialization.json.contentOrNull+import kotlinx.serialization.json.doubleOrNull+import kotlinx.serialization.json.jsonArray+import kotlinx.serialization.json.jsonObject++/** One lab test extracted from one PDF page by OpenAssistant. Pure data. */+data class ExtractedLabResult(+ val name: String,+ val value: Double?,+ val valueText: String?,+ val unit: String?,+ val referenceLow: Double?,+ val referenceHigh: Double?,+ val date: LocalDate?,+ val panel: String?,+ val page: Int,+)++/** Extraction schema, prompt and provider-side clamping for lab PDF import. */+object LabExtraction {+ const val MAX_NAME = 120+ const val MAX_UNIT = 32+ const val MAX_TEXT = 80++ const val SCHEMA: String =+ """{"type":"object","properties":{"results":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string"},"value":{},"unit":{"type":["string","null"]},"referenceLow":{"type":["number","null"]},"referenceHigh":{"type":["number","null"]},"date":{"type":["string","null"]},"panel":{"type":["string","null"]}},"required":["name"]}}},"required":["results"]}"""++ fun prompt(page: Int): String =+ "Extract ALL lab test results visible on page $page of this lab report. " ++ "For each test return name, value (number when numeric, otherwise the exact wording), " ++ "unit, referenceLow, referenceHigh, date (yyyy-MM-dd if shown), and panel/group heading if shown. " ++ "Do not invent values that are not visible."++ fun dedupeKey(r: ExtractedLabResult): String =+ listOf(+ normalizeName(r.name),+ r.date?.toString() ?: "",+ r.value?.toString() ?: r.valueText?.trim()?.lowercase().orEmpty(),+ ).joinToString("|")++ fun normalizeName(name: String): String =+ name.trim().lowercase().replace(Regex("\\s+"), " ")+}++/** Non-throwing parser: malformed model output yields no results plus a rejected count. */+object LabExtractionParser {+ private val json = Json { ignoreUnknownKeys = true; isLenient = true }++ data class Output(val results: List<ExtractedLabResult>, val rejectedRows: Int)++ fun parse(raw: String, page: Int): Output {+ val root: JsonElement = runCatching { json.parseToJsonElement(raw) }.getOrNull() ?: return Output(emptyList(), 1)+ val rows: JsonArray = when (root) {+ is JsonArray -> root+ is JsonObject -> (root["results"] as? JsonArray) ?: return Output(emptyList(), 1)+ else -> return Output(emptyList(), 1)+ }+ var rejected = 0+ val parsed = rows.mapNotNull { el ->+ val row = el as? JsonObject ?: run { rejected++; return@mapNotNull null }+ val name = (row["name"] as? JsonPrimitive)?.contentOrNull?.trim().orEmpty()+ if (name.isBlank()) { rejected++; return@mapNotNull null }+ val rawValue = row["value"]+ val numeric = (rawValue as? JsonPrimitive)?.let { p ->+ p.doubleOrNull ?: p.contentOrNull?.trim()?.replace(',', '.')?.toDoubleOrNull()+ }+ val valueText = if (numeric == null) {+ (rawValue as? JsonPrimitive)?.contentOrNull?.trim()?.take(LabExtraction.MAX_TEXT)?.ifBlank { null }+ } else null+ var low = (row["referenceLow"] as? JsonPrimitive)?.doubleOrNull+ var high = (row["referenceHigh"] as? JsonPrimitive)?.doubleOrNull+ if (low != null && high != null && low > high) { low = null; high = null }+ ExtractedLabResult(+ name = name.take(LabExtraction.MAX_NAME),+ value = numeric?.takeIf { it.isFinite() },+ valueText = valueText,+ unit = (row["unit"] as? JsonPrimitive)?.contentOrNull?.trim()?.take(LabExtraction.MAX_UNIT)?.ifBlank { null },+ referenceLow = low, referenceHigh = high,+ date = (row["date"] as? JsonPrimitive)?.contentOrNull?.trim()?.let {+ runCatching { LocalDate.parse(it) }.getOrNull()+ },+ panel = (row["panel"] as? JsonPrimitive)?.contentOrNull?.trim()?.take(LabExtraction.MAX_TEXT)?.ifBlank { null },+ page = page,+ )+ }+ return Output(parsed, rejected)+ }+}
health/src/main/java/com/vayunmathur/health/domain/LabTestCatalog.kt
diff --git a/health/src/main/java/com/vayunmathur/health/domain/LabTestCatalog.kt b/health/src/main/java/com/vayunmathur/health/domain/LabTestCatalog.ktnew file mode 100644index 0000000000..b30f1b974e--- /dev/null+++ b/health/src/main/java/com/vayunmathur/health/domain/LabTestCatalog.kt@@ -0,0 +1,43 @@+package com.vayunmathur.health.domain++/** Where a catalogue entry came from. No source invents reference ranges. */+enum class LabCatalogSource { Bundled, Recorded, Custom, Proposed }++/** A pickable lab test: name plus the unit/range the app actually knows. */+data class LabCatalogEntry(+ val name: String,+ val loincCode: String? = null,+ val unit: String? = null,+ val referenceLow: Double? = null,+ val referenceHigh: Double? = null,+ val panel: String? = null,+ val source: LabCatalogSource = LabCatalogSource.Custom,+)++/** Pure picker filtering over a merged catalogue. */+object LabCatalogSearch {+ fun filter(entries: List<LabCatalogEntry>, query: String): List<LabCatalogEntry> {+ val q = LabExtraction.normalizeName(query)+ if (q.isBlank()) return entries+ return entries.filter { LabExtraction.normalizeName(it.name).contains(q) }+ }++ /** Dedupe by normalized name; Recorded beats Custom beats Bundled (richest known fields win). */+ fun merge(entries: List<LabCatalogEntry>): List<LabCatalogEntry> {+ val rank = mapOf(+ LabCatalogSource.Recorded to 0, LabCatalogSource.Custom to 1,+ LabCatalogSource.Proposed to 2, LabCatalogSource.Bundled to 3,+ )+ return entries.groupBy { LabExtraction.normalizeName(it.name) }+ .values.map { group -> group.minBy { rank[it.source] ?: 9 } }+ .sortedBy { LabExtraction.normalizeName(it.name) }+ }+}++/** Extraction-to-catalogue matching by normalized name. */+object LabCatalogMatcher {+ fun match(name: String, catalog: List<LabCatalogEntry>): LabCatalogEntry? {+ val n = LabExtraction.normalizeName(name)+ return catalog.firstOrNull { LabExtraction.normalizeName(it.name) == n }+ }+}
health/src/main/java/com/vayunmathur/health/platform/AppBackupAgent.kt
diff --git a/health/src/main/java/com/vayunmathur/health/platform/AppBackupAgent.kt b/health/src/main/java/com/vayunmathur/health/platform/AppBackupAgent.ktindex cb06c5bbc8..c9246a6fbe 100644--- a/health/src/main/java/com/vayunmathur/health/platform/AppBackupAgent.kt+++ b/health/src/main/java/com/vayunmathur/health/platform/AppBackupAgent.kt@@ -21,5 +21,9 @@ class AppBackupAgent : BaseBackupAgent() { get() = healthDbConfigs(this) override val extraFiles: List<File>- get() = listOf(File(filesDir, "medical_attachments"))+ get() = listOf(+ File(filesDir, "medical_attachments"),+ // Lab-report PDFs: irreplaceable source documents linked from imported results.+ File(filesDir, "lab_documents"),+ ) }
health/src/main/java/com/vayunmathur/health/platform/LabDocumentStore.kt
diff --git a/health/src/main/java/com/vayunmathur/health/platform/LabDocumentStore.kt b/health/src/main/java/com/vayunmathur/health/platform/LabDocumentStore.ktnew file mode 100644index 0000000000..9efc16acb3--- /dev/null+++ b/health/src/main/java/com/vayunmathur/health/platform/LabDocumentStore.kt@@ -0,0 +1,54 @@+@file:OptIn(kotlin.uuid.ExperimentalUuidApi::class)++package com.vayunmathur.health.platform++import android.content.Context+import android.net.Uri+import androidx.core.content.FileProvider+import com.vayunmathur.library.log.Log+import com.vayunmathur.library.util.IntentHelper+import java.io.File+import kotlin.uuid.Uuid++/**+ * Stores lab-report PDFs under `filesDir/lab_documents` (backed up by+ * [AppBackupAgent] like `medical_attachments`). Only the file name is kept+ * in the database; picker Uris do not survive reboot.+ */+object LabDocumentStore {+ private const val TAG = "LabDocumentStore"+ const val DIR = "lab_documents"++ data class Imported(val fileName: String, val displayName: String, val sizeBytes: Long)++ fun fileFor(context: Context, fileName: String): File =+ File(File(context.filesDir, DIR).apply { mkdirs() }, fileName)++ fun uriFor(context: Context, fileName: String): Uri = FileProvider.getUriForFile(+ context, "${context.packageName}.fileprovider", fileFor(context, fileName),+ )++ fun exists(context: Context, fileName: String): Boolean = fileFor(context, fileName).isFile++ @Suppress("TooGenericExceptionCaught")+ fun import(context: Context, uri: Uri): Imported? {+ val displayName = IntentHelper.getFileName(context, uri) ?: "lab-report.pdf"+ val fileName = "lab_${Uuid.random()}.pdf"+ val dest = fileFor(context, fileName)+ return try {+ context.contentResolver.openInputStream(uri)?.use { input ->+ dest.outputStream().use { output -> input.copyTo(output) }+ } ?: return null+ if (dest.length() == 0L) { dest.delete(); return null }+ Imported(fileName, displayName, dest.length())+ } catch (e: Exception) {+ Log.error(TAG, "Could not import lab PDF", e)+ dest.delete()+ null+ }+ }++ fun delete(context: Context, fileName: String) {+ runCatching { fileFor(context, fileName).delete() }+ }+}
health/src/main/java/com/vayunmathur/health/platform/LabPdfRenderer.kt
diff --git a/health/src/main/java/com/vayunmathur/health/platform/LabPdfRenderer.kt b/health/src/main/java/com/vayunmathur/health/platform/LabPdfRenderer.ktnew file mode 100644index 0000000000..c94ab16906--- /dev/null+++ b/health/src/main/java/com/vayunmathur/health/platform/LabPdfRenderer.kt@@ -0,0 +1,68 @@+package com.vayunmathur.health.platform++import android.content.Context+import android.graphics.Bitmap+import android.graphics.Color+import android.graphics.pdf.PdfRenderer+import android.os.ParcelFileDescriptor+import com.vayunmathur.library.log.Log+import java.io.File++/**+ * Health-local PDF page rendering for OpenAssistant extraction.+ *+ * The repo's Rust PDF engine lives inside the :pdf app module, which no+ * other app may depend on, so this uses the platform [PdfRenderer] (no new+ * dependency). Pages are rendered once to cache PNGs at a width the vision+ * tower accepts; the tower itself downsamples/walks budgets provider-side.+ */+object LabPdfRenderer {+ private const val TAG = "LabPdfRenderer"+ const val MAX_PAGES = 50+ private const val TARGET_WIDTH = 1240++ data class Rendered(val pageCount: Int, val images: List<File>, val failedPages: List<Int>)++ @Suppress("TooGenericExceptionCaught")+ fun render(context: Context, pdf: File): Rendered {+ val outDir = File(context.cacheDir, "lab_import_pages").apply { mkdirs() }+ outDir.listFiles()?.forEach { it.delete() }+ var descriptor: ParcelFileDescriptor? = null+ var renderer: PdfRenderer? = null+ try {+ descriptor = ParcelFileDescriptor.open(pdf, ParcelFileDescriptor.MODE_READ_ONLY)+ renderer = PdfRenderer(descriptor)+ val count = renderer.pageCount+ val images = mutableListOf<File>()+ val failed = mutableListOf<Int>()+ for (index in 0 until minOf(count, MAX_PAGES)) {+ try {+ renderer.openPage(index).use { page ->+ val scale = TARGET_WIDTH.toFloat() / page.width.coerceAtLeast(1)+ val bitmap = Bitmap.createBitmap(+ TARGET_WIDTH,+ (page.height * scale).toInt().coerceAtLeast(1),+ Bitmap.Config.ARGB_8888,+ )+ bitmap.eraseColor(Color.WHITE)+ page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)+ val file = File(outDir, "page-${index + 1}.png")+ file.outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }+ bitmap.recycle()+ images.add(file)+ }+ } catch (e: Exception) {+ Log.error(TAG, "Page ${index + 1} render failed", e)+ failed.add(index + 1)+ }+ }+ if (count > MAX_PAGES) {+ for (p in MAX_PAGES + 1..count) failed.add(p)+ }+ return Rendered(count, images, failed)+ } finally {+ runCatching { renderer?.close() }+ runCatching { descriptor?.close() }+ }+ }+}
health/src/main/java/com/vayunmathur/health/platform/MedicalLabImportOps.kt
diff --git a/health/src/main/java/com/vayunmathur/health/platform/MedicalLabImportOps.kt b/health/src/main/java/com/vayunmathur/health/platform/MedicalLabImportOps.ktnew file mode 100644index 0000000000..909dacf444--- /dev/null+++ b/health/src/main/java/com/vayunmathur/health/platform/MedicalLabImportOps.kt@@ -0,0 +1,230 @@+@file:OptIn(kotlin.uuid.ExperimentalUuidApi::class)++package com.vayunmathur.health.platform++import android.content.Context+import android.content.Intent+import android.net.Uri+import androidx.lifecycle.viewModelScope+import com.vayunmathur.health.data.LabDocument+import com.vayunmathur.health.data.LabResultEntry+import com.vayunmathur.health.data.LabTestCatalogEntry+import com.vayunmathur.health.data.MedicalKind+import com.vayunmathur.health.data.ReferenceCatalog+import com.vayunmathur.health.domain.ExtractedLabResult+import com.vayunmathur.health.domain.LabCatalogEntry+import com.vayunmathur.health.domain.LabCatalogMatcher+import com.vayunmathur.health.domain.LabCatalogSource+import com.vayunmathur.health.domain.LabExtraction+import com.vayunmathur.health.domain.LabExtractionParser+import com.vayunmathur.sdk.openassistant.OpenAssistant+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import java.time.Instant+import kotlin.uuid.Uuid++/**+ * PDF lab import: pick -> store PDF -> render pages -> OpenAssistant vision+ * extraction -> review -> confirm writes. Nothing is written to the lab+ * tables before [confirmLabImport]; extraction failures are reported per+ * page and a total failure deletes the stored PDF and writes nothing.+ */+fun MedicalViewModel.startLabPdfImport(uri: Uri) {+ val app = getApplication<android.app.Application>()+ labImportStateFlow.value = MedicalViewModel.LabImportState(+ phase = MedicalViewModel.LabImportPhase.Working,+ )+ viewModelScope.launch {+ val assistant = OpenAssistant(app)+ if (!assistant.isAvailable()) {+ failLabImport(app, null, "OpenAssistant is not installed, so lab PDFs cannot be read.")+ return@launch+ }+ val imported = withContext(Dispatchers.IO) { LabDocumentStore.import(app, uri) }+ ?: run { failLabImport(app, null, "That PDF could not be read."); return@launch }+ val documentId = Uuid.random().toString()+ try {+ val rendered = withContext(Dispatchers.IO) {+ LabPdfRenderer.render(app, LabDocumentStore.fileFor(app, imported.fileName))+ }+ if (rendered.images.isEmpty()) {+ failLabImport(app, imported.fileName, "No page of that PDF could be rendered.")+ return@launch+ }+ val failures = rendered.failedPages.map { "Page $it could not be rendered." }.toMutableList()+ val results = mutableListOf<ExtractedLabResult>()+ var rejected = 0+ for (image in rendered.images) {+ val page = image.nameWithoutExtension.removePrefix("page-").toIntOrNull() ?: continue+ try {+ val raw = assistant.generateJsonWithImages(+ LabExtraction.prompt(page), LabExtraction.SCHEMA, listOf(image.absolutePath),+ )+ val parsed = LabExtractionParser.parse(raw, page)+ results += parsed.results+ rejected += parsed.rejectedRows+ } catch (e: Exception) {+ failures += "Page $page: ${e.message ?: "extraction failed"}"+ }+ }+ if (rejected > 0) failures += "$rejected extracted row(s) were malformed and dropped."+ if (results.isEmpty()) {+ failLabImport(+ app, imported.fileName,+ failures.firstOrNull() ?: "No lab results were found in that PDF.",+ )+ return@launch+ }+ val catalog = buildLabCatalog()+ val matched = results.mapNotNull { r ->+ LabCatalogMatcher.match(r.name, catalog)?.let { LabExtraction.normalizeName(r.name) }+ }.toSet()+ labImportStateFlow.value = MedicalViewModel.LabImportState(+ phase = MedicalViewModel.LabImportPhase.Review,+ documentId = documentId,+ fileName = imported.fileName,+ displayName = imported.displayName,+ pageCount = rendered.pageCount,+ results = results,+ matchedNames = matched,+ failures = failures,+ )+ } catch (e: Exception) {+ failLabImport(app, imported.fileName, e.message ?: "Lab PDF import failed.")+ }+ }+}++private fun MedicalViewModel.failLabImport(app: Context, fileName: String?, message: String) {+ fileName?.let { LabDocumentStore.delete(app, it) }+ labImportStateFlow.value = MedicalViewModel.LabImportState(+ phase = MedicalViewModel.LabImportPhase.Failed, error = message,+ )+}++/** Catalogue from app-known data only: recorded tests, custom entries, bundled LOINC names/units. */+suspend fun MedicalViewModel.buildLabCatalog(): List<LabCatalogEntry> {+ val recorded = repository.getLabResultsFlow().first()+ .groupBy { LabExtraction.normalizeName(it.displayName) }+ .values.map { group ->+ val latest = group.maxBy { it.takenAt }+ LabCatalogEntry(+ latest.displayName, latest.loincCode, latest.unit,+ latest.referenceLow, latest.referenceHigh, latest.panel, LabCatalogSource.Recorded,+ )+ }+ val custom = repository.getLabCatalogEntries().map {+ LabCatalogEntry(it.displayName, it.loincCode, it.unit, it.referenceLow, it.referenceHigh, it.panel, LabCatalogSource.Custom)+ }+ val bundled = runCatching { ReferenceCatalog.browseLabs() }.getOrDefault(emptyList()).map {+ LabCatalogEntry(it.name, it.code, it.unit, null, null, null, LabCatalogSource.Bundled)+ }+ return com.vayunmathur.health.domain.LabCatalogSearch.merge(recorded + custom + bundled)+}++/** Persists a genuinely new test name as a custom catalogue entry (no invented data). */+fun MedicalViewModel.ensureLabCatalogEntry(name: String, unit: String?) {+ viewModelScope.launch {+ val catalog = buildLabCatalog()+ if (LabCatalogMatcher.match(name, catalog) == null) {+ repository.upsertLabCatalogEntry(+ LabTestCatalogEntry(+ id = Uuid.random().toString(), displayName = name.trim(),+ unit = unit?.ifBlank { null },+ ),+ )+ }+ }+}++fun MedicalViewModel.removeExtractedResult(index: Int) {+ labImportStateFlow.value = labImportStateFlow.value.copy(+ results = labImportStateFlow.value.results.filterIndexed { i, _ -> i != index },+ )+}++fun MedicalViewModel.cancelLabImport() {+ val state = labImportStateFlow.value+ if (state.fileName.isNotBlank()) {+ LabDocumentStore.delete(getApplication(), state.fileName)+ }+ labImportStateFlow.value = MedicalViewModel.LabImportState()+}++/** The only writer in the import flow. Dedupe: same normalized test + date + value is skipped. */+fun MedicalViewModel.confirmLabImport() {+ val state = labImportStateFlow.value+ if (state.phase != MedicalViewModel.LabImportPhase.Review) return+ viewModelScope.launch {+ val catalog = buildLabCatalog()+ val existingKeys = repository.getLabResultsFlow().first().map { entry ->+ LabExtraction.dedupeKey(+ ExtractedLabResult(+ entry.displayName, entry.value, entry.valueText, entry.unit,+ entry.referenceLow, entry.referenceHigh,+ entry.takenAt.toLocalDate(), entry.panel, entry.sourcePage ?: 0,+ ),+ )+ }.toMutableSet()+ repository.upsertLabDocument(+ LabDocument(+ id = state.documentId, fileName = state.fileName, displayName = state.displayName,+ sizeBytes = LabDocumentStore.fileFor(getApplication(), state.fileName).length(),+ pageCount = state.pageCount, importedAt = Instant.now(),+ ),+ )+ for (result in state.results) {+ val key = LabExtraction.dedupeKey(result)+ if (key in existingKeys) continue+ existingKeys += key+ val match = LabCatalogMatcher.match(result.name, catalog)+ if (match == null) {+ repository.upsertLabCatalogEntry(+ LabTestCatalogEntry(+ id = Uuid.random().toString(), displayName = result.name.trim(),+ unit = result.unit, referenceLow = result.referenceLow,+ referenceHigh = result.referenceHigh, panel = result.panel,+ ),+ )+ }+ val entry = LabResultEntry(+ id = Uuid.random().toString(),+ loincCode = match?.loincCode,+ displayName = match?.name ?: result.name.trim(),+ value = result.value, valueText = result.valueText,+ unit = result.unit ?: match?.unit,+ referenceLow = result.referenceLow ?: match?.referenceLow,+ referenceHigh = result.referenceHigh ?: match?.referenceHigh,+ takenAt = result.date?.toInstant() ?: today().toInstant(),+ sourceDocumentId = state.documentId, sourcePage = result.page, panel = result.panel,+ )+ repository.upsertLabResult(entry)+ repository.markPending(MedicalKind.LabResult, entry.id)+ mirrorLabResult(entry.id)+ }+ labImportStateFlow.value = MedicalViewModel.LabImportState()+ }+}++/** Opens the source PDF in the system viewer (the pdf app when installed). */+fun openLabDocument(context: Context, fileName: String): Boolean {+ if (!LabDocumentStore.exists(context, fileName)) return false+ val intent = Intent(Intent.ACTION_VIEW).apply {+ setDataAndType(LabDocumentStore.uriFor(context, fileName), "application/pdf")+ addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_ACTIVITY_NEW_TASK)+ }+ return runCatching { context.startActivity(intent); true }.getOrDefault(false)+}++/**+ * Deletes the PDF but keeps its results: their source link then honestly+ * reports the document as gone instead of pretending it never existed.+ */+fun MedicalViewModel.deleteLabDocument(document: LabDocument) {+ viewModelScope.launch {+ repository.deleteLabDocument(document)+ LabDocumentStore.delete(getApplication(), document.fileName)+ }+}
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 b44a9cb479..61d4433f59 100644--- a/health/src/main/java/com/vayunmathur/health/platform/MedicalViewModel.kt+++ b/health/src/main/java/com/vayunmathur/health/platform/MedicalViewModel.kt@@ -119,6 +119,32 @@ class MedicalViewModel( val doseEvents: StateFlow<List<DoseEvent>> = repository.getDoseEventsFlow() .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList()) + val labDocuments: StateFlow<List<com.vayunmathur.health.data.LabDocument>> =+ repository.getLabDocumentsFlow()+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())++ val labCatalogEntries: StateFlow<List<com.vayunmathur.health.data.LabTestCatalogEntry>> =+ repository.getLabCatalogFlow()+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())++ /** PDF lab import state machine (see MedicalLabImportOps). */+ enum class LabImportPhase { Idle, Working, Review, Failed }++ data class LabImportState(+ val phase: LabImportPhase = LabImportPhase.Idle,+ val documentId: String = "",+ val fileName: String = "",+ val displayName: String = "",+ val pageCount: Int = 0,+ val results: List<com.vayunmathur.health.domain.ExtractedLabResult> = emptyList(),+ val matchedNames: Set<String> = emptySet(),+ val failures: List<String> = emptyList(),+ val error: String? = null,+ )++ internal val labImportStateFlow = MutableStateFlow(LabImportState())+ val labImportState: StateFlow<LabImportState> = labImportStateFlow.asStateFlow()+ internal val syncingState = MutableStateFlow(false) val syncing: StateFlow<Boolean> = syncingState.asStateFlow() @@ -247,6 +273,9 @@ class MedicalViewModel( val referenceHigh: String = "", val takenOn: LocalDate = today(), val note: String = "",+ val sourceDocumentId: String? = null,+ val sourcePage: Int? = null,+ val panel: String? = null, ) internal val allergyDraftState = MutableStateFlow(AllergyDraft())@@ -316,6 +345,9 @@ class MedicalViewModel( referenceHigh = entry.referenceHigh?.let { formatNumber(it) }.orEmpty(), takenOn = entry.takenAt.toLocalDate(), note = entry.note.orEmpty(),+ sourceDocumentId = entry.sourceDocumentId,+ sourcePage = entry.sourcePage,+ panel = entry.panel, ) } }
health/src/main/java/com/vayunmathur/health/ui/AddLabResultPage.kt
diff --git a/health/src/main/java/com/vayunmathur/health/ui/AddLabResultPage.kt b/health/src/main/java/com/vayunmathur/health/ui/AddLabResultPage.ktindex ff468ed738..e7b35e4b30 100644--- a/health/src/main/java/com/vayunmathur/health/ui/AddLabResultPage.kt+++ b/health/src/main/java/com/vayunmathur/health/ui/AddLabResultPage.kt@@ -15,7 +15,11 @@ import androidx.compose.ui.unit.dp import com.vayunmathur.health.R import com.vayunmathur.health.Route import com.vayunmathur.health.platform.MedicalViewModel+import com.vayunmathur.health.platform.deleteLabDocument+import com.vayunmathur.health.platform.openLabDocument import com.vayunmathur.health.platform.saveLabDraft+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.util.AppMessages import com.vayunmathur.health.ui.components.PickerField import com.vayunmathur.library.ui.DetailScaffold import com.vayunmathur.library.ui.ExperimentalMaterial3Api@@ -45,6 +49,8 @@ private const val TAKEN_KEY = "add-lab/taken" @Composable fun AddLabResultPage(backStack: NavBackStack<Route>, viewModel: MedicalViewModel) { val draft by viewModel.labDraft.collectAsState()+ val documents by viewModel.labDocuments.collectAsState()+ val context = androidx.compose.ui.platform.LocalContext.current ResultEffect<LocalDate>(TAKEN_KEY) { picked -> viewModel.editLabDraft { it.copy(takenOn = picked) }@@ -127,5 +133,32 @@ fun AddLabResultPage(backStack: NavBackStack<Route>, viewModel: MedicalViewModel singleLine = false, ) }++ draft.sourceDocumentId?.let { documentId ->+ val document = documents.firstOrNull { it.id == documentId }+ FormSection(title = stringResource(R.string.lab_import_source_pdf)) {+ if (document == null) {+ Text(stringResource(R.string.lab_import_pdf_gone))+ } else {+ Text(+ listOfNotNull(+ document.displayName,+ draft.sourcePage?.let {+ stringResource(R.string.lab_import_from_pdf, it)+ },+ draft.panel,+ ).joinToString(" · "),+ )+ Button(onClick = {+ if (!openLabDocument(context, document.fileName)) {+ AppMessages.show(context.getString(R.string.lab_import_pdf_gone))+ }+ }) { Text(stringResource(R.string.lab_import_view_pdf)) }+ TextButton(onClick = { viewModel.deleteLabDocument(document) }) {+ Text(stringResource(R.string.lab_import_delete_pdf))+ }+ }+ }+ } } }
health/src/main/java/com/vayunmathur/health/ui/CatalogPickerPage.kt
diff --git a/health/src/main/java/com/vayunmathur/health/ui/CatalogPickerPage.kt b/health/src/main/java/com/vayunmathur/health/ui/CatalogPickerPage.ktindex 5c79096331..d760650bda 100644--- a/health/src/main/java/com/vayunmathur/health/ui/CatalogPickerPage.kt+++ b/health/src/main/java/com/vayunmathur/health/ui/CatalogPickerPage.kt@@ -24,7 +24,11 @@ import com.vayunmathur.health.R import com.vayunmathur.health.Route import com.vayunmathur.health.data.ReferenceCatalog import com.vayunmathur.health.data.VaccineCatalog+import com.vayunmathur.health.domain.LabCatalogEntry+import com.vayunmathur.health.domain.LabCatalogSearch import com.vayunmathur.health.platform.MedicalViewModel+import com.vayunmathur.health.platform.buildLabCatalog+import com.vayunmathur.health.platform.ensureLabCatalogEntry import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.ScaffoldSearch import com.vayunmathur.library.ui.ExperimentalMaterial3Api@@ -37,19 +41,15 @@ import kotlinx.serialization.Serializable /** How long to wait for typing to stop before searching. */ private const val SEARCH_DEBOUNCE_MS = 180L- /** Which catalogue [CatalogPickerPage] is searching, and therefore which draft field it fills in. */ @Serializable enum class CatalogKind { /** CVX vaccine codes. */ Vaccine,- /** RxNorm ingredients — the first medication step. */ MedicationIngredient,- /** RxNorm products for one ingredient — the second step, giving strength and dose form. */ MedicationProduct,- /** RxNorm ingredients again, but recorded as an allergen rather than something taken. */ Allergen, @@ -67,9 +67,7 @@ enum class CatalogKind { * every dropdown component in `:library:ui` renders its options eagerly. * * It writes the choice straight into the ViewModel's draft rather than posting it back through- * `LocalNavResultRegistry`. That registry only works for dialog destinations: `NavDisplay` composes- * one destination at a time, so a full-screen picker disposes the form underneath it, and a result- * posted to a `SharedFlow` with no replay would arrive at a collector that no longer exists.+ * `LocalNavResultRegistry` (dialog-only; the form underneath is disposed while this is open). * * Free text is always available as the last row. The medication catalogue is a gitignored build * artefact, so a clean checkout has no medication list at all, and even with one a user may be@@ -91,9 +89,7 @@ fun CatalogPickerPage( if (route.kind != CatalogKind.Vaccine) ReferenceCatalog.prepare() } - // Searching on every keystroke restarts the query and rebuilds the whole list between two- // frames of typing. The queries themselves are sub-millisecond, but the churn is visible, so- // wait for a pause. Clearing is exempt: emptying the field should feel instant.+ // Debounced search: wait for a typing pause; clearing is instant. var settledQuery by remember { mutableStateOf("") } LaunchedEffect(query) { if (query.isEmpty()) {@@ -109,7 +105,7 @@ fun CatalogPickerPage( var products by remember { mutableStateOf<List<ReferenceCatalog.Medication>>(emptyList()) } var allergens by remember { mutableStateOf<List<ReferenceCatalog.Ingredient>>(emptyList()) } var conditions by remember { mutableStateOf<List<ReferenceCatalog.Condition>>(emptyList()) }- var labs by remember { mutableStateOf<List<ReferenceCatalog.LabTest>>(emptyList()) }+ var labs by remember { mutableStateOf<List<LabCatalogEntry>>(emptyList()) } LaunchedEffect(route.kind, route.ingredient, settledQuery, catalogStatus) { when (route.kind) {@@ -130,8 +126,8 @@ fun CatalogPickerPage( conditions = if (settledQuery.isBlank()) emptyList() else ReferenceCatalog.searchConditions(settledQuery) CatalogKind.LabTest ->- labs = if (settledQuery.isBlank()) emptyList()- else ReferenceCatalog.searchLabs(settledQuery)+ // Blank query lists the merged catalogue; a query filters it.+ labs = LabCatalogSearch.filter(viewModel.buildLabCatalog(), settledQuery) } } @@ -166,20 +162,29 @@ fun CatalogPickerPage( backStack.pop() } - // The unit LOINC suggests comes along with the test, which is right far more often than not and- // stays editable. It is only filled in when the field is still empty, so it cannot overwrite a- // unit the user typed before going to pick the test.- fun chooseLab(code: String?, name: String, unit: String?) {+ // Pre-fills unit/range where known, only into still-empty fields.+ fun chooseLab(entry: LabCatalogEntry) { viewModel.editLabDraft { it.copy(- loincCode = code,- displayName = name,- unit = if (it.unit.isBlank()) unit.orEmpty() else it.unit,+ loincCode = entry.loincCode,+ displayName = entry.name,+ unit = if (it.unit.isBlank()) entry.unit.orEmpty() else it.unit,+ referenceLow = if (it.referenceLow.isBlank()) {+ entry.referenceLow?.let { v -> formatLabNumber(v) }.orEmpty()+ } else it.referenceLow,+ referenceHigh = if (it.referenceHigh.isBlank()) {+ entry.referenceHigh?.let { v -> formatLabNumber(v) }.orEmpty()+ } else it.referenceHigh, ) } backStack.pop() } + fun chooseLabTyped(name: String) {+ viewModel.ensureLabCatalogEntry(name, null)+ chooseLab(LabCatalogEntry(name = name.trim()))+ }+ // Back clears the search before leaving, matching ListPage. With the field in the // scaffold's search slot there is nowhere else for a back press to sensibly go first. BackHandler(enabled = query.isNotEmpty()) { query = "" }@@ -308,13 +313,11 @@ fun CatalogPickerPage( ) } - CatalogKind.LabTest -> items(labs, key = { it.code }) { lab ->+ CatalogKind.LabTest -> items(labs, key = { it.loincCode ?: it.name }) { lab -> ListItem( headlineContent = { Text(lab.name) }, supportingContent = lab.unit?.let { unit -> { Text(unit) } },- modifier = Modifier.clickable {- chooseLab(lab.code, lab.name, lab.unit)- },+ modifier = Modifier.clickable { chooseLab(lab) }, ) } }@@ -331,7 +334,7 @@ fun CatalogPickerPage( CatalogKind.MedicationProduct -> chooseProduct(null, typed, null) CatalogKind.Allergen -> chooseAllergen(null, typed) CatalogKind.Condition -> chooseCondition(null, typed)- CatalogKind.LabTest -> chooseLab(null, typed, null)+ CatalogKind.LabTest -> chooseLabTyped(typed) } }, )@@ -341,3 +344,6 @@ fun CatalogPickerPage( } } }++private fun formatLabNumber(value: Double): String =+ if (value == value.toLong().toDouble()) value.toLong().toString() else value.toString()
health/src/main/java/com/vayunmathur/health/ui/LabImportReviewPage.kt
diff --git a/health/src/main/java/com/vayunmathur/health/ui/LabImportReviewPage.kt b/health/src/main/java/com/vayunmathur/health/ui/LabImportReviewPage.ktnew file mode 100644index 0000000000..e0c871f512--- /dev/null+++ b/health/src/main/java/com/vayunmathur/health/ui/LabImportReviewPage.kt@@ -0,0 +1,64 @@+package com.vayunmathur.health.ui++import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.res.stringResource+import com.vayunmathur.health.R+import com.vayunmathur.health.Route+import com.vayunmathur.health.domain.LabExtraction+import com.vayunmathur.health.platform.MedicalViewModel+import com.vayunmathur.health.platform.cancelLabImport+import com.vayunmathur.health.platform.confirmLabImport+import com.vayunmathur.health.platform.removeExtractedResult+import com.vayunmathur.library.ui.DetailScaffold+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.FormSection+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.util.NavBackStack++/**+ * Confirmation gate for PDF lab import: extracted rows are shown (new+ * catalogue tests marked) and only [confirmLabImport] writes anything.+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun LabImportReviewPage(backStack: NavBackStack<Route>, viewModel: MedicalViewModel) {+ val state by viewModel.labImportState.collectAsState()+ androidx.activity.compose.BackHandler { viewModel.cancelLabImport(); backStack.pop() }+ DetailScaffold(+ title = stringResource(R.string.lab_import_review_title),+ backStack = backStack,+ actions = {+ TextButton(+ enabled = state.results.isNotEmpty(),+ onClick = { viewModel.confirmLabImport(); backStack.pop() },+ ) { Text(stringResource(R.string.lab_import_confirm)) }+ },+ ) {+ FormSection(title = state.displayName) {+ state.failures.forEach { Text(it) }+ if (state.results.isEmpty()) {+ Text(stringResource(R.string.no_matches))+ }+ state.results.forEachIndexed { index, result ->+ val isNew = LabExtraction.normalizeName(result.name) !in state.matchedNames+ Text(+ listOfNotNull(+ result.name,+ result.value?.toString() ?: result.valueText,+ result.unit,+ result.date?.toString(),+ stringResource(R.string.lab_import_from_pdf, result.page),+ if (isNew) stringResource(R.string.lab_import_new_test) else null,+ result.panel,+ ).joinToString(" · "),+ )+ TextButton(onClick = { viewModel.removeExtractedResult(index) }) {+ Text(stringResource(R.string.lab_import_remove))+ }+ }+ }+ }+}
health/src/main/java/com/vayunmathur/health/ui/MedicalPage.kt
diff --git a/health/src/main/java/com/vayunmathur/health/ui/MedicalPage.kt b/health/src/main/java/com/vayunmathur/health/ui/MedicalPage.ktindex b201df3075..3210d6408e 100644--- a/health/src/main/java/com/vayunmathur/health/ui/MedicalPage.kt+++ b/health/src/main/java/com/vayunmathur/health/ui/MedicalPage.kt@@ -1,6 +1,7 @@ package com.vayunmathur.health.ui import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.layout.Arrangement import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect@@ -29,6 +30,8 @@ import com.vayunmathur.health.data.MedicationEntry import com.vayunmathur.health.data.VaccinationEntry import com.vayunmathur.health.platform.MedicalViewModel import com.vayunmathur.health.platform.PersonalHealthRecords+import com.vayunmathur.health.platform.startLabPdfImport+import com.vayunmathur.library.util.AppMessages import com.vayunmathur.health.platform.importFromHealthConnect import com.vayunmathur.health.platform.recordDoseTaken import com.vayunmathur.health.ui.components.HealthRow@@ -42,6 +45,7 @@ import com.vayunmathur.library.ui.IconClose import com.vayunmathur.library.ui.IconMedication import com.vayunmathur.library.ui.IconMonitorHeart import com.vayunmathur.library.ui.IconScience+import com.vayunmathur.library.ui.IconUpload import com.vayunmathur.library.ui.IconVaccine import com.vayunmathur.library.ui.IconWarning import com.vayunmathur.library.ui.LazyListScaffold@@ -100,6 +104,20 @@ fun MedicalPage(backStack: NavBackStack<Route>, viewModel: MedicalViewModel) { LaunchedEffect(Unit) { viewModel.importFromHealthConnect() } + val labImportState by viewModel.labImportState.collectAsState()+ var labImportNavigated by remember { mutableStateOf(false) }+ LaunchedEffect(labImportState.phase) {+ when (labImportState.phase) {+ MedicalViewModel.LabImportPhase.Review -> if (!labImportNavigated) { labImportNavigated = true; backStack.add(Route.LabImportReview) }+ MedicalViewModel.LabImportPhase.Failed -> { labImportState.error?.let { AppMessages.show(it) }; labImportNavigated = false }+ MedicalViewModel.LabImportPhase.Idle -> labImportNavigated = false+ MedicalViewModel.LabImportPhase.Working -> AppMessages.show("Reading PDF…")+ }+ }+ val pickLabPdf = rememberLauncherForActivityResult(+ ActivityResultContracts.OpenDocument(),+ ) { uri -> if (uri != null) viewModel.startLabPdfImport(uri) }+ val expanded = remember { mutableStateListOf<String>() } var pastMedsExpanded by remember { mutableStateOf(false) } var fabExpanded by remember { mutableStateOf(false) }@@ -178,6 +196,14 @@ fun MedicalPage(backStack: NavBackStack<Route>, viewModel: MedicalViewModel) { text = { Text(stringResource(R.string.add_lab_result)) }, icon = { IconScience() }, )+ FloatingActionButtonMenuItem(+ onClick = {+ fabExpanded = false+ pickLabPdf.launch(arrayOf("application/pdf"))+ },+ text = { Text(stringResource(R.string.import_lab_pdf)) },+ icon = { IconUpload() },+ ) FloatingActionButtonMenuItem( onClick = { viewModel.startMedicationDraft()
health/src/main/java/com/vayunmathur/health/ui/NavigationEntries.kt
diff --git a/health/src/main/java/com/vayunmathur/health/ui/NavigationEntries.kt b/health/src/main/java/com/vayunmathur/health/ui/NavigationEntries.ktindex dfc34772b6..299d19e229 100644--- a/health/src/main/java/com/vayunmathur/health/ui/NavigationEntries.kt+++ b/health/src/main/java/com/vayunmathur/health/ui/NavigationEntries.kt@@ -152,6 +152,9 @@ internal fun EntryProviderScope<Route>.medicalEntries( entry<Route.EditLabResult>(metadata = ListDetailPage()) { AddLabResultPage(backStack, medicalViewModel) }+ entry<Route.LabImportReview>(metadata = ListDetailPage()) {+ LabImportReviewPage(backStack, medicalViewModel)+ } entry<Route.CatalogPicker>(metadata = ListDetailPage()) { CatalogPickerPage(backStack, medicalViewModel, it) }
health/src/main/res/values/strings.xml
diff --git a/health/src/main/res/values/strings.xml b/health/src/main/res/values/strings.xmlindex 296ea5229e..f84e37b633 100644--- a/health/src/main/res/values/strings.xml+++ b/health/src/main/res/values/strings.xml@@ -537,6 +537,17 @@ <string name="field_reference_high">Normal to</string> <!-- AddLabResultPage: Date the sample was taken. Noun phrase --> <string name="field_taken_on">Taken on</string>+ <string name="import_lab_pdf">Import lab PDF</string>+ <string name="lab_import_review_title">Review lab results</string>+ <string name="lab_import_confirm">Add results</string>+ <string name="lab_import_new_test">New test</string>+ <string name="lab_import_from_pdf">PDF import · page %1$d</string>+ <string name="lab_import_source_pdf">Source PDF</string>+ <string name="lab_import_view_pdf">View PDF</string>+ <string name="lab_import_delete_pdf">Delete PDF</string>+ <string name="lab_import_pdf_gone">Source document no longer available</string>+ <string name="lab_import_working">Reading PDF…</string>+ <string name="lab_import_remove">Remove</string> <!-- AboutYouPage: Screen of standing facts about the user. Noun phrase --> <string name="about_you">About you</string> <!-- AboutYouPage: Overline above the current-status summary. Noun phrase -->
health/src/main/res/xml/file_paths.xml
diff --git a/health/src/main/res/xml/file_paths.xml b/health/src/main/res/xml/file_paths.xmlindex da90e63908..99a2400d36 100644--- a/health/src/main/res/xml/file_paths.xml+++ b/health/src/main/res/xml/file_paths.xml@@ -4,4 +4,5 @@ <!-- Vaccination card scans. Shared out read-only so an external viewer can open one; see com.vayunmathur.health.platform.AttachmentStore. --> <files-path name="medical_attachments" path="medical_attachments/" />+ <files-path name="lab_documents" path="lab_documents/" /> </paths>
health/src/test/java/com/vayunmathur/health/data/MigrationsTest.kt
diff --git a/health/src/test/java/com/vayunmathur/health/data/MigrationsTest.kt b/health/src/test/java/com/vayunmathur/health/data/MigrationsTest.ktindex c1d8a9bafc..611315c412 100644--- a/health/src/test/java/com/vayunmathur/health/data/MigrationsTest.kt+++ b/health/src/test/java/com/vayunmathur/health/data/MigrationsTest.kt@@ -102,18 +102,18 @@ class MigrationsTest { } @Test- fun `migration chain spans version 1 to 13 without gaps`() {+ fun `migration chain spans version 1 to 14 without gaps`() { val migrations = HealthDatabase.migrations val sorted = migrations.sortedBy { it.startVersion } assertTrue(sorted.first().startVersion == 1)- assertTrue(sorted.last().endVersion == 13)+ assertTrue(sorted.last().endVersion == 14) for (i in 0 until sorted.size - 1) { assertTrue(sorted[i].endVersion == sorted[i + 1].startVersion, "gap after version ${sorted[i].endVersion}") } } @Test- fun `v1 database upgrades to v13 shape and keeps its rows`() {+ fun `v1 database upgrades to v14 shape and keeps its rows`() { val file = File(context.cacheDir, "migration-v1-probe.db") file.delete() val raw = SQLiteDatabase.openOrCreateDatabase(file, null)
health/src/test/java/com/vayunmathur/health/domain/LabCatalogTest.kt
diff --git a/health/src/test/java/com/vayunmathur/health/domain/LabCatalogTest.kt b/health/src/test/java/com/vayunmathur/health/domain/LabCatalogTest.ktnew file mode 100644index 0000000000..9712b61b39--- /dev/null+++ b/health/src/test/java/com/vayunmathur/health/domain/LabCatalogTest.kt@@ -0,0 +1,34 @@+package com.vayunmathur.health.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++class LabCatalogTest {+ private val catalog = listOf(+ LabCatalogEntry("Glucose", "2345-7", "mg/dL", 70.0, 99.0, null, LabCatalogSource.Recorded),+ LabCatalogEntry("Sodium", "2951-2", "mmol/L", null, null, null, LabCatalogSource.Bundled),+ LabCatalogEntry("Hemoglobin A1c", null, "%", null, null, null, LabCatalogSource.Custom),+ )++ @Test fun pickerFilterBlankShowsCatalogue() {+ assertEquals(3, LabCatalogSearch.filter(catalog, "").size)+ assertEquals(listOf("Glucose"), LabCatalogSearch.filter(catalog, "glu").map { it.name })+ assertEquals(listOf("Hemoglobin A1c"), LabCatalogSearch.filter(catalog, "A1C").map { it.name })+ }++ @Test fun matcherMatchesNormalizedName() {+ assertEquals("Glucose", LabCatalogMatcher.match(" glucose ", catalog)?.name)+ assertEquals("Hemoglobin A1c", LabCatalogMatcher.match("hemoglobin a1c", catalog)?.name)+ assertEquals(null, LabCatalogMatcher.match("Ferritin", catalog))+ }++ @Test fun mergeDedupesByNamePreferringRecorded() {+ val merged = LabCatalogSearch.merge(+ catalog + LabCatalogEntry("glucose", null, "g/L", null, null, null, LabCatalogSource.Bundled),+ )+ assertEquals(3, merged.size)+ assertEquals("mg/dL", merged.first { it.name == "Glucose" }.unit)+ assertTrue(merged.first { it.name == "Glucose" }.source == LabCatalogSource.Recorded)+ }+}
health/src/test/java/com/vayunmathur/health/domain/LabExtractionTest.kt
diff --git a/health/src/test/java/com/vayunmathur/health/domain/LabExtractionTest.kt b/health/src/test/java/com/vayunmathur/health/domain/LabExtractionTest.ktnew file mode 100644index 0000000000..ca930bf646--- /dev/null+++ b/health/src/test/java/com/vayunmathur/health/domain/LabExtractionTest.kt@@ -0,0 +1,48 @@+package com.vayunmathur.health.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++class LabExtractionTest {+ @Test fun parsesNumericAndQualitativeRows() {+ val out = LabExtractionParser.parse(+ """{"results":[{"name":"Glucose","value":95,"unit":"mg/dL","referenceLow":70,"referenceHigh":99,"date":"2026-01-02","panel":"Metabolic"},{"name":"HIV screen","value":"Not detected","date":"2026-01-02"}]}""",+ page = 1,+ )+ assertEquals(2, out.results.size)+ assertEquals(95.0, out.results[0].value)+ assertEquals("Metabolic", out.results[0].panel)+ assertEquals(1, out.results[0].page)+ assertNull(out.results[1].value)+ assertEquals("Not detected", out.results[1].valueText)+ }++ @Test fun malformedOutputRejected() {+ assertTrue(LabExtractionParser.parse("not json", 1).results.isEmpty())+ assertTrue(LabExtractionParser.parse("""{"nope":[]}""", 1).results.isEmpty())+ val out = LabExtractionParser.parse("""{"results":[{"name":" "},{"name":"Sodium","value":"140"}]}""", 2)+ assertEquals(1, out.results.size)+ assertEquals(1, out.rejectedRows)+ assertEquals(140.0, out.results[0].value)+ }++ @Test fun clampsLengthsAndDropsInvertedRange() {+ val long = "x".repeat(300)+ val out = LabExtractionParser.parse(+ """{"results":[{"name":"$long","value":1,"unit":"$long","referenceLow":10,"referenceHigh":5,"date":"bad"}]}""",+ page = 3,+ )+ val r = out.results.single()+ assertTrue(r.name.length <= LabExtraction.MAX_NAME)+ assertTrue((r.unit?.length ?: 0) <= LabExtraction.MAX_UNIT)+ assertNull(r.referenceLow); assertNull(r.referenceHigh); assertNull(r.date)+ }++ @Test fun dedupeKeyIgnoresCaseAndWhitespace() {+ val a = ExtractedLabResult(" Glucose ", 95.0, null, "mg/dL", null, null, kotlinx.datetime.LocalDate(2026,1,2), null, 1)+ val b = a.copy(name = "glucose")+ assertEquals(LabExtraction.dedupeKey(a), LabExtraction.dedupeKey(b))+ }+}
health/src/test/java/com/vayunmathur/health/platform/HealthBackupAgentTest.kt
diff --git a/health/src/test/java/com/vayunmathur/health/platform/HealthBackupAgentTest.kt b/health/src/test/java/com/vayunmathur/health/platform/HealthBackupAgentTest.ktindex 18b4d793cb..67a21ae187 100644--- a/health/src/test/java/com/vayunmathur/health/platform/HealthBackupAgentTest.kt+++ b/health/src/test/java/com/vayunmathur/health/platform/HealthBackupAgentTest.kt@@ -84,7 +84,7 @@ class HealthBackupAgentTest { ) assertEquals("passwords-db", DB_NAME) assertEquals(- listOf("medical_attachments"),+ listOf("medical_attachments", "lab_documents"), agent.extraFiles.map { it.name }, ) }
health/src/test/java/com/vayunmathur/health/platform/LabImportOpsTest.kt
diff --git a/health/src/test/java/com/vayunmathur/health/platform/LabImportOpsTest.kt b/health/src/test/java/com/vayunmathur/health/platform/LabImportOpsTest.ktnew file mode 100644index 0000000000..51eb5167f6--- /dev/null+++ b/health/src/test/java/com/vayunmathur/health/platform/LabImportOpsTest.kt@@ -0,0 +1,76 @@+package com.vayunmathur.health.platform++import android.app.Application+import android.os.Looper+import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.health.data.HealthDatabase+import com.vayunmathur.health.data.HealthRepository+import com.vayunmathur.health.domain.ExtractedLabResult+import com.vayunmathur.library.util.databases+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.first+
Diff truncated.