qualia_client_core/wellfair/
personal_profile.rs1use std::fs::{self, OpenOptions};
4use std::io::{BufRead, BufReader, Write};
5use std::path::{Path, PathBuf};
6
7use serde::{Deserialize, Serialize};
8
9pub const CONTACTS_FILE: &str = "wellfair/emergency_contacts.jsonl";
10pub const MAX_CONTACTS: usize = 32;
11
12#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
13pub struct EmergencyContact {
14 pub id: String,
15 pub display_name: String,
16 pub relationship: String,
17 pub phone: Option<String>,
18 pub email: Option<String>,
19 pub notes: Option<String>,
20 pub created_at_unix: u32,
21}
22
23pub struct EmergencyContactStore {
24 path: PathBuf,
25}
26
27impl EmergencyContactStore {
28 pub fn open(storage_root: impl AsRef<Path>) -> std::io::Result<Self> {
30 let path = storage_root.as_ref().join(CONTACTS_FILE);
31 if let Some(parent) = path.parent() {
32 fs::create_dir_all(parent)?;
33 }
34 if !path.exists() {
35 OpenOptions::new().create(true).write(true).open(&path)?;
36 }
37 Ok(Self { path })
38 }
39
40 pub fn append(&self, contact: &EmergencyContact) -> std::io::Result<()> {
42 let line =
43 serde_json::to_string(contact).map_err(|e| std::io::Error::other(e.to_string()))?;
44 let mut file = OpenOptions::new().append(true).open(&self.path)?;
45 writeln!(file, "{line}")?;
46 file.sync_all()?;
47 Ok(())
48 }
49
50 pub fn list(&self) -> std::io::Result<Vec<EmergencyContact>> {
52 let file = fs::File::open(&self.path)?;
53 let reader = BufReader::new(file);
54 let mut out = Vec::new();
55 for line in reader.lines() {
56 let line = line?;
57 if line.trim().is_empty() {
58 continue;
59 }
60 if let Ok(c) = serde_json::from_str::<EmergencyContact>(&line) {
61 out.push(c);
62 }
63 }
64 if out.len() > MAX_CONTACTS {
65 out.drain(0..out.len() - MAX_CONTACTS);
66 }
67 Ok(out)
68 }
69}
70
71pub fn new_contact_id(name: &str, unix: u32) -> String {
73 use sha2::{Digest, Sha256};
74 let digest = Sha256::digest(format!("{name}:{unix}").as_bytes());
75 format!("ec-{}", hex::encode(&digest[..4]))
76}
77
78#[cfg(test)]
79mod tests {
80 use super::*;
81
82 #[test]
83 fn emergency_contact_round_trip() {
84 let dir = tempfile::tempdir().unwrap();
85 let store = EmergencyContactStore::open(dir.path()).unwrap();
86 let c = EmergencyContact {
87 id: new_contact_id("Alex", 100),
88 display_name: "Alex".into(),
89 relationship: "sibling".into(),
90 phone: Some("+1-555-0100".into()),
91 email: None,
92 notes: None,
93 created_at_unix: 100,
94 };
95 store.append(&c).unwrap();
96 let listed = store.list().unwrap();
97 assert_eq!(listed.len(), 1);
98 assert_eq!(listed[0].display_name, "Alex");
99 }
100}