1use serde::{Deserialize, Serialize};
6use sha2::{Digest, Sha256};
7
8use crate::record::{
9 EpistemicStatus, EvidenceType, InstantBridge, RecordEnvelope, SensitivityClass,
10};
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
13#[serde(rename_all = "snake_case")]
14pub enum AdministrationStatus {
15 Taken,
16 Skipped,
17 Overdue,
18}
19
20#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
21pub struct MedicationCatalogEntry {
22 pub id: String,
23 pub name: String,
24 pub dose: String,
25 pub route: String,
26 pub schedule_times: Vec<String>,
28 pub prescriber: Option<String>,
29 pub ceased_at_unix: Option<u32>,
30 #[serde(skip_serializing_if = "Option::is_none", default)]
33 pub ceased_at_instant: Option<InstantBridge>,
34 pub created_at_unix: u32,
35 #[serde(skip_serializing_if = "Option::is_none", default)]
38 pub created_at_instant: Option<InstantBridge>,
39}
40
41#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
42pub struct MedicationAdministration {
43 pub id: String,
44 pub medication_id: String,
45 pub medication_name: String,
46 pub status: AdministrationStatus,
47 pub administered_at_unix: u32,
48 #[serde(skip_serializing_if = "Option::is_none", default)]
51 pub administered_at_instant: Option<InstantBridge>,
52 pub notes: Option<String>,
53}
54
55#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
56pub struct DietEntry {
57 pub id: String,
58 pub description: String,
59 pub meal_type: String,
60 pub calories_kcal: Option<u32>,
61 pub logged_at_unix: u32,
62 #[serde(skip_serializing_if = "Option::is_none", default)]
65 pub logged_at_instant: Option<InstantBridge>,
66}
67
68fn content_hash_hex(payload: &str) -> String {
69 hex::encode(Sha256::digest(payload.as_bytes()).as_slice())
70}
71
72fn stable_suffix(parts: &[&str]) -> String {
73 let joined = parts.join(":");
74 let digest = Sha256::digest(joined.as_bytes());
75 hex::encode(&digest[..4])
76}
77
78pub fn new_medication_id(name: &str, created_unix: u32) -> String {
80 format!(
81 "urn:wellfair:medication:{}",
82 stable_suffix(&[name, &created_unix.to_string()])
83 )
84}
85
86pub fn new_administration_id(med_id: &str, unix: u32) -> String {
88 format!(
89 "urn:wellfair:med_admin:{}",
90 stable_suffix(&[med_id, &unix.to_string()])
91 )
92}
93
94pub fn new_diet_id(description: &str, unix: u32) -> String {
96 format!(
97 "urn:wellfair:diet:{}",
98 stable_suffix(&[description, &unix.to_string()])
99 )
100}
101
102fn self_reported_envelope(
103 id: &str,
104 owner_did: &str,
105 author_did: &str,
106 asserted_unix: u32,
107 payload_json: &str,
108) -> RecordEnvelope {
109 RecordEnvelope {
110 id: id.to_string(),
111 owner_did: owner_did.to_string(),
112 author_did: author_did.to_string(),
113 proxy_did: None,
114 epistemic_status: EpistemicStatus::Asserted,
115 evidence_type: EvidenceType::SelfReported,
116 sensitivity: SensitivityClass::Restricted,
117 asserted_time_unix: asserted_unix,
118 asserted_instant: None,
119 valid_time_start_unix: Some(asserted_unix),
120 valid_time_start_instant: None,
121 valid_time_end_unix: None,
122 valid_time_end_instant: None,
123 predecessor_id: None,
124 blob_hash: Some(content_hash_hex(payload_json)),
125 tombstone: false,
126 }
127}
128
129pub struct EnvelopeWithSummary {
130 pub envelope: RecordEnvelope,
131 pub summary: String,
132}
133
134pub fn medication_envelope(
136 entry: &MedicationCatalogEntry,
137 owner_did: &str,
138 author_did: &str,
139) -> EnvelopeWithSummary {
140 let payload = serde_json::to_string(entry).unwrap_or_default();
141 let summary = serde_json::json!({
142 "name": entry.name,
143 "dose": entry.dose,
144 "route": entry.route,
145 "schedule_times": entry.schedule_times,
146 "ceased": entry.ceased_at_unix.is_some(),
147 })
148 .to_string();
149 EnvelopeWithSummary {
150 envelope: self_reported_envelope(
151 &entry.id,
152 owner_did,
153 author_did,
154 entry.created_at_unix,
155 &payload,
156 ),
157 summary,
158 }
159}
160
161pub fn administration_envelope(
163 admin: &MedicationAdministration,
164 owner_did: &str,
165 author_did: &str,
166) -> EnvelopeWithSummary {
167 let payload = serde_json::to_string(admin).unwrap_or_default();
168 let summary = serde_json::json!({
169 "medication_id": admin.medication_id,
170 "medication_name": admin.medication_name,
171 "status": admin.status,
172 "notes": admin.notes,
173 })
174 .to_string();
175 EnvelopeWithSummary {
176 envelope: self_reported_envelope(
177 &admin.id,
178 owner_did,
179 author_did,
180 admin.administered_at_unix,
181 &payload,
182 ),
183 summary,
184 }
185}
186
187pub fn diet_envelope(entry: &DietEntry, owner_did: &str, author_did: &str) -> EnvelopeWithSummary {
189 let payload = serde_json::to_string(entry).unwrap_or_default();
190 let summary = serde_json::json!({
191 "description": entry.description,
192 "meal_type": entry.meal_type,
193 "calories_kcal": entry.calories_kcal,
194 })
195 .to_string();
196 EnvelopeWithSummary {
197 envelope: self_reported_envelope(
198 &entry.id,
199 owner_did,
200 author_did,
201 entry.logged_at_unix,
202 &payload,
203 ),
204 summary,
205 }
206}
207
208#[cfg(test)]
209mod tests {
210 use super::*;
211
212 #[test]
213 fn medication_envelope_has_stable_id_prefix() {
214 let entry = MedicationCatalogEntry {
215 id: new_medication_id("Metformin", 1_700_000_000),
216 name: "Metformin".into(),
217 dose: "500mg".into(),
218 route: "oral".into(),
219 schedule_times: vec!["08:00".into()],
220 prescriber: None,
221 ceased_at_unix: None,
222 ceased_at_instant: None,
223 created_at_unix: 1_700_000_000,
224 created_at_instant: None,
225 };
226 let packed = medication_envelope(&entry, "did:wf:owner", "did:wf:owner");
227 assert!(packed.envelope.id.contains(":medication:"));
228 assert!(packed.summary.contains("Metformin"));
229 }
230}