feat(backend): dose scheduling + health stats zero-knowledge
Backend changes (frontend + tests follow in next commit): Dose scheduling: - New DoseSchedule struct (times_per_day + days_of_week) as a top-level plaintext field on Medication. Create/update requests accept it. - Revised get_adherence: computes scheduled_doses from the schedule over the period (days_of_week filtering), so missed doses are now reflected. Falls back to taken/total_logged when no schedule. Health stats zero-knowledge: - HealthStatistic model now uses opaque encrypted_data blob (like medications). Only recorded_at stays plaintext (filterable/sortable). - HealthStatResponse wire type. Handlers echo opaque blobs. - Removed the trends endpoint (server can't compute trends on ciphertext; frontend computes them client-side after decrypting). - Deleted the dead HealthData model (kept EncryptedField which it defined). Verified: backend 24 tests, 0 clippy warnings.
This commit is contained in:
parent
69faa43a72
commit
09589b3bb2
8 changed files with 270 additions and 200 deletions
|
|
@ -1,28 +1,8 @@
|
|||
use mongodb::bson::{oid::ObjectId, DateTime};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct HealthData {
|
||||
#[serde(rename = "_id", skip_serializing_if = "Option::is_none")]
|
||||
pub id: Option<ObjectId>,
|
||||
#[serde(rename = "healthDataId")]
|
||||
pub health_data_id: String,
|
||||
#[serde(rename = "userId")]
|
||||
pub user_id: String,
|
||||
#[serde(rename = "profileId")]
|
||||
pub profile_id: String,
|
||||
#[serde(rename = "familyId")]
|
||||
pub family_id: Option<String>,
|
||||
#[serde(rename = "healthData")]
|
||||
pub health_data: Vec<EncryptedField>,
|
||||
#[serde(rename = "createdAt")]
|
||||
pub created_at: DateTime,
|
||||
#[serde(rename = "updatedAt")]
|
||||
pub updated_at: DateTime,
|
||||
#[serde(rename = "dataSource")]
|
||||
pub data_source: String,
|
||||
}
|
||||
|
||||
/// The storage-layer encrypted-field wrapper used by Medication and Appointment
|
||||
/// documents. NOTE: the `HealthData` model that previously used `Vec<EncryptedField>`
|
||||
/// was dead code (no handler/route/repository) and has been removed.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct EncryptedField {
|
||||
pub encrypted: bool,
|
||||
|
|
|
|||
|
|
@ -6,19 +6,42 @@ use mongodb::{
|
|||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::models::medication::EncryptedFieldWire;
|
||||
|
||||
/// Zero-knowledge health stat: the value/unit/type/notes are encrypted inside
|
||||
/// the opaque blob; only `recorded_at` stays plaintext (filterable/sortable).
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct HealthStatistic {
|
||||
#[serde(rename = "_id", skip_serializing_if = "Option::is_none")]
|
||||
pub id: Option<ObjectId>,
|
||||
pub user_id: String,
|
||||
#[serde(rename = "type")]
|
||||
pub stat_type: String,
|
||||
pub value: f64,
|
||||
pub unit: String,
|
||||
pub notes: Option<String>,
|
||||
/// Opaque client-encrypted blob (value, unit, type, notes inside).
|
||||
#[serde(rename = "encryptedData")]
|
||||
pub encrypted_data: EncryptedFieldWire,
|
||||
/// When the reading was taken (plaintext, filterable/sortable).
|
||||
pub recorded_at: String,
|
||||
}
|
||||
|
||||
/// Wire response (what the API returns).
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct HealthStatResponse {
|
||||
pub id: String,
|
||||
pub user_id: String,
|
||||
pub encrypted_data: EncryptedFieldWire,
|
||||
pub recorded_at: String,
|
||||
}
|
||||
|
||||
impl From<HealthStatistic> for HealthStatResponse {
|
||||
fn from(s: HealthStatistic) -> Self {
|
||||
HealthStatResponse {
|
||||
id: s.id.map(|o| o.to_hex()).unwrap_or_default(),
|
||||
user_id: s.user_id,
|
||||
encrypted_data: s.encrypted_data,
|
||||
recorded_at: s.recorded_at,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct HealthStatisticsRepository {
|
||||
collection: Collection<HealthStatistic>,
|
||||
|
|
@ -31,11 +54,14 @@ impl HealthStatisticsRepository {
|
|||
}
|
||||
}
|
||||
|
||||
pub async fn create(&self, stat: &HealthStatistic) -> Result<HealthStatistic, MongoError> {
|
||||
pub async fn create(
|
||||
&self,
|
||||
stat: &HealthStatistic,
|
||||
) -> Result<Option<HealthStatistic>, MongoError> {
|
||||
let result = self.collection.insert_one(stat, None).await?;
|
||||
let mut created = stat.clone();
|
||||
created.id = Some(result.inserted_id.as_object_id().unwrap());
|
||||
Ok(created)
|
||||
created.id = result.inserted_id.as_object_id();
|
||||
Ok(Some(created))
|
||||
}
|
||||
|
||||
pub async fn find_by_user(&self, user_id: &str) -> Result<Vec<HealthStatistic>, MongoError> {
|
||||
|
|
@ -49,14 +75,22 @@ impl HealthStatisticsRepository {
|
|||
self.collection.find_one(filter, None).await
|
||||
}
|
||||
|
||||
pub async fn update(
|
||||
pub async fn update_encrypted_data(
|
||||
&self,
|
||||
id: &ObjectId,
|
||||
stat: &HealthStatistic,
|
||||
encrypted_data: EncryptedFieldWire,
|
||||
) -> Result<Option<HealthStatistic>, MongoError> {
|
||||
let filter = doc! { "_id": id };
|
||||
self.collection.replace_one(filter, stat, None).await?;
|
||||
Ok(Some(stat.clone()))
|
||||
self.collection
|
||||
.find_one_and_update(
|
||||
doc! { "_id": id },
|
||||
doc! { "$set": {
|
||||
"encryptedData.data": encrypted_data.data,
|
||||
"encryptedData.iv": encrypted_data.iv,
|
||||
"encryptedData.authTag": encrypted_data.auth_tag,
|
||||
}},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn delete(&self, id: &ObjectId) -> Result<bool, MongoError> {
|
||||
|
|
|
|||
|
|
@ -106,6 +106,8 @@ pub struct MedicationResponse {
|
|||
pub user_id: String,
|
||||
pub profile_id: String,
|
||||
pub active: bool,
|
||||
/// Dose schedule (plaintext, for adherence calc).
|
||||
pub dose_schedule: Option<DoseSchedule>,
|
||||
/// Opaque client-encrypted blob (base64 ciphertext + iv). The server stores
|
||||
/// and returns this verbatim; only the client can decrypt it.
|
||||
pub encrypted_data: EncryptedFieldWire,
|
||||
|
|
@ -132,6 +134,7 @@ impl std::convert::From<Medication> for MedicationResponse {
|
|||
user_id: m.user_id,
|
||||
profile_id: m.profile_id,
|
||||
active: m.active,
|
||||
dose_schedule: m.dose_schedule,
|
||||
encrypted_data: EncryptedFieldWire {
|
||||
data: m.medication_data.data,
|
||||
iv: m.medication_data.iv,
|
||||
|
|
@ -154,6 +157,17 @@ fn system_time_to_rfc3339(t: std::time::SystemTime) -> String {
|
|||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Plaintext dose schedule (top-level on the Medication document so the server
|
||||
/// can compute adherence without decrypting the opaque medication_data blob).
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct DoseSchedule {
|
||||
pub times_per_day: u32,
|
||||
/// Which days of the week the medication is taken. Empty = every day.
|
||||
/// Values: "mon","tue","wed","thu","fri","sat","sun" (lowercase).
|
||||
#[serde(default)]
|
||||
pub days_of_week: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Medication {
|
||||
#[serde(rename = "_id", skip_serializing_if = "Option::is_none")]
|
||||
|
|
@ -176,6 +190,9 @@ pub struct Medication {
|
|||
/// documents that predate the field (see `default_true`).
|
||||
#[serde(rename = "active", default = "default_true")]
|
||||
pub active: bool,
|
||||
/// Dose schedule for adherence calculation (plaintext, top-level).
|
||||
#[serde(rename = "doseSchedule", skip_serializing_if = "Option::is_none")]
|
||||
pub dose_schedule: Option<DoseSchedule>,
|
||||
|
||||
/// Physical pill identification (Phase 2.8 - optional)
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
|
|
@ -226,6 +243,8 @@ pub struct CreateMedicationRequest {
|
|||
/// Whether the medication is active on creation (defaults to true).
|
||||
#[serde(default = "default_true")]
|
||||
pub active: bool,
|
||||
/// Dose schedule for adherence calculation (plaintext).
|
||||
pub dose_schedule: Option<DoseSchedule>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
|
|
@ -235,6 +254,8 @@ pub struct UpdateMedicationRequest {
|
|||
pub encrypted_data: Option<EncryptedFieldWire>,
|
||||
/// Set the medication active/inactive.
|
||||
pub active: Option<bool>,
|
||||
/// Update the dose schedule.
|
||||
pub dose_schedule: Option<Option<DoseSchedule>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
|
|
@ -360,6 +381,19 @@ impl MedicationRepository {
|
|||
if let Some(active) = updates.active {
|
||||
update_doc.insert("active", active);
|
||||
}
|
||||
if let Some(schedule) = updates.dose_schedule {
|
||||
match schedule {
|
||||
Some(s) => {
|
||||
if let Ok(sched_doc) = mongodb::bson::to_document(&s) {
|
||||
update_doc.insert("doseSchedule", sched_doc);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
// Explicitly clear the schedule.
|
||||
update_doc.insert("doseSchedule", mongodb::bson::Bson::Null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let medication = self
|
||||
.collection
|
||||
|
|
@ -395,6 +429,19 @@ impl MedicationRepository {
|
|||
if let Some(active) = updates.active {
|
||||
update_doc.insert("active", active);
|
||||
}
|
||||
if let Some(schedule) = updates.dose_schedule {
|
||||
match schedule {
|
||||
Some(s) => {
|
||||
if let Ok(sched_doc) = mongodb::bson::to_document(&s) {
|
||||
update_doc.insert("doseSchedule", sched_doc);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
// Explicitly clear the schedule.
|
||||
update_doc.insert("doseSchedule", mongodb::bson::Bson::Null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let medication = self
|
||||
.collection
|
||||
|
|
@ -438,6 +485,7 @@ mod tests {
|
|||
created_at: DateTime::now(),
|
||||
updated_at: DateTime::now(),
|
||||
active: true,
|
||||
dose_schedule: None,
|
||||
pill_identification: None,
|
||||
};
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue