1use serde::{Deserialize, Serialize};
16use uuid::Uuid;
17
18use crate::record::{
19 EpistemicStatus, EvidenceType, InstantBridge, RecordEnvelope, SensitivityClass,
20};
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub struct ResponseOption {
25 pub value: u8,
26 pub label: &'static str,
27}
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub struct SeverityBand {
33 pub min: u32,
34 pub max: u32,
35 pub label: &'static str,
36 pub interpretation: &'static str,
37}
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub struct FlagRule {
43 pub item_index: usize,
44 pub min_value: u8,
45 pub message: &'static str,
46}
47
48#[derive(Debug, Clone, Copy)]
50pub struct Instrument {
51 pub id: &'static str,
52 pub name: &'static str,
53 pub domain: &'static str,
54 pub attribution: &'static str,
55 pub prompt: &'static str,
56 pub items: &'static [&'static str],
57 pub options: &'static [ResponseOption],
58 pub bands: &'static [SeverityBand],
59 pub flags: &'static [FlagRule],
60 pub disclaimer: &'static str,
61}
62
63impl Instrument {
64 pub fn max_score(&self) -> u32 {
66 let max_opt = self
67 .options
68 .iter()
69 .map(|o| o.value as u32)
70 .max()
71 .unwrap_or(0);
72 max_opt * self.items.len() as u32
73 }
74}
75
76const FREQ_0_3: &[ResponseOption] = &[
78 ResponseOption {
79 value: 0,
80 label: "Not at all",
81 },
82 ResponseOption {
83 value: 1,
84 label: "Several days",
85 },
86 ResponseOption {
87 value: 2,
88 label: "More than half the days",
89 },
90 ResponseOption {
91 value: 3,
92 label: "Nearly every day",
93 },
94];
95
96const DISCLAIMER: &str = "This is a self-monitoring aid, not a diagnosis — a score can't diagnose a \
97condition, only a qualified clinician can. If you're in crisis or thinking of harming yourself, \
98contact a local crisis line or emergency services now.";
99
100pub static PHQ9: Instrument = Instrument {
102 id: "phq9",
103 name: "PHQ-9 (Patient Health Questionnaire-9)",
104 domain: "depression",
105 attribution: "Developed by Drs Spitzer, Kroenke & Williams (Pfizer). Free to reproduce; no permission required.",
106 prompt: "Over the last 2 weeks, how often have you been bothered by any of the following problems?",
107 items: &[
108 "Little interest or pleasure in doing things",
109 "Feeling down, depressed, or hopeless",
110 "Trouble falling or staying asleep, or sleeping too much",
111 "Feeling tired or having little energy",
112 "Poor appetite or overeating",
113 "Feeling bad about yourself — or that you are a failure or have let yourself or your family down",
114 "Trouble concentrating on things, such as reading the newspaper or watching television",
115 "Moving or speaking so slowly that other people could have noticed — or the opposite, being so fidgety or restless that you have been moving around a lot more than usual",
116 "Thoughts that you would be better off dead, or of hurting yourself in some way",
117 ],
118 options: FREQ_0_3,
119 bands: &[
120 SeverityBand {
121 min: 0,
122 max: 4,
123 label: "Minimal",
124 interpretation: "Your responses suggest minimal depressive symptoms right now.",
125 },
126 SeverityBand {
127 min: 5,
128 max: 9,
129 label: "Mild",
130 interpretation: "Mild depressive symptoms. It can help to keep an eye on how you're doing and re-check in a couple of weeks.",
131 },
132 SeverityBand {
133 min: 10,
134 max: 14,
135 label: "Moderate",
136 interpretation: "Moderate symptoms. A conversation with a clinician or counsellor may help.",
137 },
138 SeverityBand {
139 min: 15,
140 max: 19,
141 label: "Moderately severe",
142 interpretation: "Moderately severe symptoms. Support from a clinician is recommended.",
143 },
144 SeverityBand {
145 min: 20,
146 max: 27,
147 label: "Severe",
148 interpretation: "Severe symptoms. Please consider reaching out to a clinician or someone you trust soon.",
149 },
150 ],
151 flags: &[FlagRule {
152 item_index: 8,
153 min_value: 1,
154 message: "You indicated some thoughts of being better off dead or of hurting yourself. You deserve support — please reach out to someone you trust or a crisis line. If you're in immediate danger, contact emergency services.",
155 }],
156 disclaimer: DISCLAIMER,
157};
158
159pub static GAD7: Instrument = Instrument {
161 id: "gad7",
162 name: "GAD-7 (Generalized Anxiety Disorder-7)",
163 domain: "anxiety",
164 attribution: "Developed by Drs Spitzer, Kroenke & Williams (Pfizer). Free to reproduce; no permission required.",
165 prompt: "Over the last 2 weeks, how often have you been bothered by the following problems?",
166 items: &[
167 "Feeling nervous, anxious, or on edge",
168 "Not being able to stop or control worrying",
169 "Worrying too much about different things",
170 "Trouble relaxing",
171 "Being so restless that it is hard to sit still",
172 "Becoming easily annoyed or irritable",
173 "Feeling afraid, as if something awful might happen",
174 ],
175 options: FREQ_0_3,
176 bands: &[
177 SeverityBand {
178 min: 0,
179 max: 4,
180 label: "Minimal",
181 interpretation: "Your responses suggest minimal anxiety symptoms right now.",
182 },
183 SeverityBand {
184 min: 5,
185 max: 9,
186 label: "Mild",
187 interpretation: "Mild anxiety symptoms. Keeping an eye on how you're doing can help.",
188 },
189 SeverityBand {
190 min: 10,
191 max: 14,
192 label: "Moderate",
193 interpretation: "Moderate symptoms. A conversation with a clinician or counsellor may help.",
194 },
195 SeverityBand {
196 min: 15,
197 max: 21,
198 label: "Severe",
199 interpretation: "Severe symptoms. Support from a clinician is recommended.",
200 },
201 ],
202 flags: &[],
203 disclaimer: DISCLAIMER,
204};
205
206pub fn instruments() -> [&'static Instrument; 2] {
208 [&PHQ9, &GAD7]
209}
210
211pub fn instrument(id: &str) -> Option<&'static Instrument> {
213 match id {
214 "phq9" => Some(&PHQ9),
215 "gad7" => Some(&GAD7),
216 _ => None,
217 }
218}
219
220#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
222pub struct AssessmentResult {
223 pub id: String,
224 pub instrument_id: String,
225 pub responses: Vec<u8>,
226 pub total: u32,
227 pub band_label: String,
228 pub interpretation: String,
229 #[serde(default, skip_serializing_if = "Vec::is_empty")]
231 pub flags: Vec<String>,
232 pub taken_at_unix: u32,
233 #[serde(skip_serializing_if = "Option::is_none", default)]
236 pub taken_at_instant: Option<InstantBridge>,
237}
238
239impl AssessmentResult {
240 pub fn taken_at(&self) -> InstantBridge {
243 self.taken_at_instant
244 .unwrap_or_else(|| InstantBridge::from_coarse(self.taken_at_unix))
245 }
246}
247
248pub fn score(
251 instrument: &Instrument,
252 responses: &[u8],
253 taken_at_unix: u32,
254) -> Result<AssessmentResult, String> {
255 if responses.len() != instrument.items.len() {
256 return Err(format!(
257 "{} expects {} responses, got {}",
258 instrument.id,
259 instrument.items.len(),
260 responses.len()
261 ));
262 }
263 let max_val = instrument
264 .options
265 .iter()
266 .map(|o| o.value)
267 .max()
268 .unwrap_or(0);
269 for (i, &r) in responses.iter().enumerate() {
270 if r > max_val {
271 return Err(format!(
272 "response {r} for item {} exceeds the maximum {max_val}",
273 i + 1
274 ));
275 }
276 }
277 let total: u32 = responses.iter().map(|&r| r as u32).sum();
278 let band = instrument
279 .bands
280 .iter()
281 .find(|b| total >= b.min && total <= b.max)
282 .ok_or_else(|| format!("no severity band covers total {total}"))?;
283 let flags: Vec<String> = instrument
284 .flags
285 .iter()
286 .filter(|f| {
287 responses
288 .get(f.item_index)
289 .is_some_and(|&r| r >= f.min_value)
290 })
291 .map(|f| f.message.to_string())
292 .collect();
293 Ok(AssessmentResult {
294 id: Uuid::new_v4().to_string(),
295 instrument_id: instrument.id.to_string(),
296 responses: responses.to_vec(),
297 total,
298 band_label: band.label.to_string(),
299 interpretation: band.interpretation.to_string(),
300 flags,
301 taken_at_unix,
302 taken_at_instant: Some(InstantBridge::from_coarse(taken_at_unix)),
303 })
304}
305
306pub fn assessment_record_id(uuid: &str) -> String {
310 format!("urn:wellfair:wellbeing_assessment:{uuid}")
311}
312
313pub fn build_assessment_envelope(
315 result: &AssessmentResult,
316 owner_did: &str,
317 author_did: &str,
318 asserted_unix: u32,
319) -> RecordEnvelope {
320 RecordEnvelope {
321 id: assessment_record_id(&result.id),
322 owner_did: owner_did.to_string(),
323 author_did: author_did.to_string(),
324 proxy_did: None,
325 epistemic_status: EpistemicStatus::Asserted,
326 evidence_type: EvidenceType::SelfReported,
327 sensitivity: SensitivityClass::Restricted,
328 asserted_time_unix: asserted_unix,
329 asserted_instant: None,
330 valid_time_start_unix: Some(result.taken_at_unix),
331 valid_time_start_instant: result.taken_at_instant,
332 valid_time_end_unix: None,
333 valid_time_end_instant: None,
334 predecessor_id: None,
335 blob_hash: None,
336 tombstone: false,
337 }
338}
339
340pub fn assessment_summary(result: &AssessmentResult) -> String {
342 serde_json::to_string(result).unwrap_or_default()
343}
344
345pub fn parse_assessment(json: &str) -> Option<AssessmentResult> {
347 serde_json::from_str(json).ok()
348}
349
350#[derive(Debug, Clone, Serialize, Deserialize)]
354pub struct InstrumentDto {
355 pub id: String,
356 pub name: String,
357 pub domain: String,
358 pub attribution: String,
359 pub prompt: String,
360 pub items: Vec<String>,
361 pub options: Vec<(u8, String)>,
363 pub bands: Vec<(u32, u32, String, String)>,
365 pub max_score: u32,
366 pub disclaimer: String,
367}
368
369pub fn instrument_dto(inst: &Instrument) -> InstrumentDto {
371 InstrumentDto {
372 id: inst.id.to_string(),
373 name: inst.name.to_string(),
374 domain: inst.domain.to_string(),
375 attribution: inst.attribution.to_string(),
376 prompt: inst.prompt.to_string(),
377 items: inst.items.iter().map(|s| s.to_string()).collect(),
378 options: inst
379 .options
380 .iter()
381 .map(|o| (o.value, o.label.to_string()))
382 .collect(),
383 bands: inst
384 .bands
385 .iter()
386 .map(|b| {
387 (
388 b.min,
389 b.max,
390 b.label.to_string(),
391 b.interpretation.to_string(),
392 )
393 })
394 .collect(),
395 max_score: inst.max_score(),
396 disclaimer: inst.disclaimer.to_string(),
397 }
398}
399
400#[cfg(test)]
401mod tests {
402 use super::*;
403
404 #[test]
405 fn ships_phq9_and_gad7_with_correct_shape() {
406 assert_eq!(instruments().len(), 2);
407 assert_eq!(PHQ9.items.len(), 9);
408 assert_eq!(GAD7.items.len(), 7);
409 assert_eq!(PHQ9.max_score(), 27);
410 assert_eq!(GAD7.max_score(), 21);
411 assert!(instrument("phq9").is_some());
412 assert!(instrument("gad7").is_some());
413 assert!(instrument("bdi2").is_none());
414 }
415
416 #[test]
417 fn phq9_bands_cover_every_possible_total_without_gaps() {
418 for total in 0..=PHQ9.max_score() {
420 let hits: Vec<_> = PHQ9
421 .bands
422 .iter()
423 .filter(|b| total >= b.min && total <= b.max)
424 .collect();
425 assert_eq!(hits.len(), 1, "total {total} must map to exactly one band");
426 }
427 }
428
429 #[test]
430 fn gad7_bands_cover_every_possible_total_without_gaps() {
431 for total in 0..=GAD7.max_score() {
432 let hits: Vec<_> = GAD7
433 .bands
434 .iter()
435 .filter(|b| total >= b.min && total <= b.max)
436 .collect();
437 assert_eq!(hits.len(), 1, "total {total} must map to exactly one band");
438 }
439 }
440
441 #[test]
442 fn phq9_scoring_matches_known_bands() {
443 let r = score(&PHQ9, &[0; 9], 100).unwrap();
445 assert_eq!(r.total, 0);
446 assert_eq!(r.band_label, "Minimal");
447 assert!(r.flags.is_empty());
448
449 let r = score(&PHQ9, &[3; 9], 100).unwrap();
451 assert_eq!(r.total, 27);
452 assert_eq!(r.band_label, "Severe");
453 assert_eq!(r.flags.len(), 1);
454
455 assert_eq!(
457 score(&PHQ9, &[2, 2, 2, 2, 2, 0, 0, 0, 0], 1).unwrap().total,
458 10
459 );
460 assert_eq!(
461 score(&PHQ9, &[2, 2, 2, 2, 2, 0, 0, 0, 0], 1)
462 .unwrap()
463 .band_label,
464 "Moderate"
465 );
466 assert_eq!(
467 score(&PHQ9, &[3, 3, 3, 3, 2, 0, 0, 0, 0], 1).unwrap().total,
468 14
469 );
470 assert_eq!(
471 score(&PHQ9, &[3, 3, 3, 3, 2, 0, 0, 0, 0], 1)
472 .unwrap()
473 .band_label,
474 "Moderate"
475 );
476 assert_eq!(
477 score(&PHQ9, &[3, 3, 3, 3, 3, 0, 0, 0, 0], 1).unwrap().total,
478 15
479 );
480 assert_eq!(
481 score(&PHQ9, &[3, 3, 3, 3, 3, 0, 0, 0, 0], 1)
482 .unwrap()
483 .band_label,
484 "Moderately severe"
485 );
486 }
487
488 #[test]
489 fn phq9_self_harm_flag_fires_even_at_a_low_total() {
490 let mut resp = [0u8; 9];
492 resp[8] = 1;
493 let r = score(&PHQ9, &resp, 1).unwrap();
494 assert_eq!(r.total, 1);
495 assert_eq!(r.band_label, "Minimal");
496 assert_eq!(
497 r.flags.len(),
498 1,
499 "self-harm flag must fire regardless of total"
500 );
501 }
502
503 #[test]
504 fn gad7_scoring_matches_known_bands() {
505 assert_eq!(score(&GAD7, &[0; 7], 1).unwrap().band_label, "Minimal");
506 assert_eq!(score(&GAD7, &[3; 7], 1).unwrap().band_label, "Severe");
507 assert_eq!(score(&GAD7, &[2, 2, 2, 2, 2, 0, 0], 1).unwrap().total, 10);
508 assert_eq!(
509 score(&GAD7, &[2, 2, 2, 2, 2, 0, 0], 1).unwrap().band_label,
510 "Moderate"
511 );
512 }
513
514 #[test]
515 fn scoring_is_fail_closed_on_bad_input() {
516 assert!(score(&PHQ9, &[0; 8], 1).is_err());
518 assert!(score(&GAD7, &[0, 0, 0, 0, 0, 0, 4], 1).is_err());
520 }
521
522 #[test]
523 fn result_summary_round_trips_and_envelope_kind() {
524 let r = score(&PHQ9, &[1; 9], 42).unwrap();
525 let summary = assessment_summary(&r);
526 let back = parse_assessment(&summary).expect("reconstructs");
527 assert_eq!(r, back);
528 let env = build_assessment_envelope(&r, "did:o", "did:a", 42);
529 assert!(env.id.contains(":wellbeing_assessment:"));
530 assert_eq!(env.sensitivity, SensitivityClass::Restricted);
531 }
532
533 #[test]
534 fn instrument_dto_carries_items_options_and_bands() {
535 let dto = instrument_dto(&PHQ9);
536 assert_eq!(dto.items.len(), 9);
537 assert_eq!(dto.options.len(), 4);
538 assert_eq!(dto.max_score, 27);
539 assert!(dto.bands.iter().any(|(_, _, label, _)| label == "Severe"));
540 assert!(!dto.disclaimer.is_empty());
541 }
542}