Skip to main content

qualia_client_core/wellfair/
med_reminders.rs

1//! Local medication reminder prefs and due-slot computation (Q6 MED-01..13).
2
3use std::fs;
4use std::path::Path;
5
6use chrono::{NaiveTime, Timelike};
7use serde::{Deserialize, Serialize};
8
9use super::journal::JournalEntry;
10
11pub const PREFS_FILE: &str = "wellfair/med_reminder_prefs.json";
12
13#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
14pub struct MedReminderPrefs {
15    pub enabled: bool,
16    pub permission_granted: bool,
17    #[serde(default, skip_serializing_if = "Option::is_none")]
18    pub permission_granted_at_unix: Option<u32>,
19}
20
21impl Default for MedReminderPrefs {
22    fn default() -> Self {
23        Self {
24            enabled: false,
25            permission_granted: false,
26            permission_granted_at_unix: None,
27        }
28    }
29}
30
31#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
32pub struct DueMedReminder {
33    pub medication_id: String,
34    pub medication_name: String,
35    pub schedule_slot: String,
36    /// Minutes until due (negative = overdue today).
37    pub minutes_until_due: i32,
38}
39
40/// Loads prefs.
41pub fn load_prefs(storage_root: impl AsRef<Path>) -> MedReminderPrefs {
42    let path = storage_root.as_ref().join(PREFS_FILE);
43    if !path.exists() {
44        return MedReminderPrefs::default();
45    }
46    fs::read_to_string(&path)
47        .ok()
48        .and_then(|s| serde_json::from_str(&s).ok())
49        .unwrap_or_default()
50}
51
52/// Saves prefs.
53pub fn save_prefs(storage_root: impl AsRef<Path>, prefs: &MedReminderPrefs) -> std::io::Result<()> {
54    let path = storage_root.as_ref().join(PREFS_FILE);
55    if let Some(parent) = path.parent() {
56        fs::create_dir_all(parent)?;
57    }
58    let json =
59        serde_json::to_string_pretty(prefs).map_err(|e| std::io::Error::other(e.to_string()))?;
60    fs::write(&path, json)
61}
62
63fn parse_hhmm(slot: &str) -> Option<NaiveTime> {
64    let parts: Vec<_> = slot.trim().split(':').collect();
65    if parts.len() != 2 {
66        return None;
67    }
68    let h: u32 = parts[0].parse().ok()?;
69    let m: u32 = parts[1].parse().ok()?;
70    NaiveTime::from_hms_opt(h, m, 0)
71}
72
73/// Compute due/overdue slots for active medications from journal summaries.
74pub fn compute_due_reminders(
75    journal: &[JournalEntry],
76    now_local: NaiveTime,
77    window_minutes: i32,
78) -> Vec<DueMedReminder> {
79    let now_mins = (now_local.hour() * 60 + now_local.minute()) as i32;
80    let mut out = Vec::new();
81
82    for entry in journal {
83        if entry.kind != "medication" {
84            continue;
85        }
86        let Some(summary) = &entry.summary else {
87            continue;
88        };
89        let Ok(json) = serde_json::from_str::<serde_json::Value>(summary) else {
90            continue;
91        };
92        if json
93            .get("ceased")
94            .and_then(|v| v.as_bool())
95            .unwrap_or(false)
96        {
97            continue;
98        }
99        let name = json
100            .get("name")
101            .and_then(|v| v.as_str())
102            .unwrap_or("medication")
103            .to_string();
104        let slots = json
105            .get("schedule_times")
106            .and_then(|v| v.as_array())
107            .map(|arr| {
108                arr.iter()
109                    .filter_map(|v| v.as_str().map(|s| s.to_string()))
110                    .collect::<Vec<_>>()
111            })
112            .unwrap_or_default();
113
114        for slot in slots {
115            let Some(t) = parse_hhmm(&slot) else {
116                continue;
117            };
118            let slot_mins = (t.hour() * 60 + t.minute()) as i32;
119            let minutes_until = slot_mins - now_mins;
120            if minutes_until.abs() <= window_minutes {
121                out.push(DueMedReminder {
122                    medication_id: entry.id.clone(),
123                    medication_name: name.clone(),
124                    schedule_slot: slot,
125                    minutes_until_due: minutes_until,
126                });
127            }
128        }
129    }
130
131    out.sort_by_key(|r| r.minutes_until_due);
132    out
133}
134
135#[cfg(test)]
136mod tests {
137    use super::*;
138
139    fn med_entry(id: &str, summary: &str) -> JournalEntry {
140        JournalEntry {
141            id: id.into(),
142            kind: "medication".into(),
143            asserted_time_unix: 0,
144            asserted_instant: wellfare_core::record::InstantBridge::default(),
145            evidence_type: "SelfReported".into(),
146            sensitivity: "Restricted".into(),
147            blob_hash: None,
148            source: "test".into(),
149            committed_unix: 0,
150            summary: Some(summary.into()),
151        }
152    }
153
154    #[test]
155    fn prefs_round_trip() {
156        let dir = tempfile::tempdir().unwrap();
157        let mut prefs = MedReminderPrefs::default();
158        prefs.permission_granted = true;
159        prefs.enabled = true;
160        prefs.permission_granted_at_unix = Some(100);
161        save_prefs(dir.path(), &prefs).unwrap();
162        let loaded = load_prefs(dir.path());
163        assert_eq!(loaded, prefs);
164    }
165
166    #[test]
167    fn due_reminder_within_window() {
168        let summary = r#"{"name":"Metformin","schedule_times":["08:00","20:00"],"ceased":false}"#;
169        let journal = vec![med_entry("urn:wellfair:medication:x", summary)];
170        let now = NaiveTime::from_hms_opt(8, 5, 0).unwrap();
171        let due = compute_due_reminders(&journal, now, 30);
172        assert_eq!(due.len(), 1);
173        assert_eq!(due[0].schedule_slot, "08:00");
174        assert_eq!(due[0].minutes_until_due, -5);
175    }
176
177    #[test]
178    fn ceased_medication_excluded() {
179        let summary = r#"{"name":"Old","schedule_times":["08:00"],"ceased":true}"#;
180        let journal = vec![med_entry("urn:wellfair:medication:y", summary)];
181        let now = NaiveTime::from_hms_opt(8, 0, 0).unwrap();
182        assert!(compute_due_reminders(&journal, now, 30).is_empty());
183    }
184}