Skip to main content

wellfare_core/
welfare_support.rs

1//! Welfare support — assistance needs, welfare streams, and government letters.
2//!
3//! Cold-path Restricted profile records for the WellFair vault (audit LIF-08..14).
4//! These capture the practical machinery of receiving support: the *needs* a person has
5//! identified, the government/benefit *streams* they are applying for or receiving, and the
6//! *letters* they get back. All three are owner self-reported, epistemically Asserted, and
7//! held at Restricted sensitivity — this is welfare paperwork, not a public disclosure.
8//!
9//! This module is deliberately SEPARATE from `life_records.rs`; it owns its own record kinds
10//! (`assistance_need`, `welfare_stream`, `government_letter`).
11
12use serde::{Deserialize, Serialize};
13use uuid::Uuid;
14
15use crate::record::{
16    EpistemicStatus, EvidenceType, InstantBridge, RecordEnvelope, SensitivityClass,
17};
18
19/// How pressing an identified assistance need is.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
21#[serde(rename_all = "snake_case")]
22pub enum Urgency {
23    Low,
24    Moderate,
25    High,
26    Critical,
27}
28
29impl Default for Urgency {
30    fn default() -> Self {
31        Self::Moderate
32    }
33}
34
35/// Lifecycle of a welfare / benefit stream from the owner's point of view.
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
37#[serde(rename_all = "snake_case")]
38pub enum StreamStatus {
39    Applied,
40    Active,
41    Suspended,
42    Ceased,
43    Rejected,
44}
45
46impl Default for StreamStatus {
47    fn default() -> Self {
48        Self::Applied
49    }
50}
51
52/// An assistance need the owner (or their proxy) has identified — e.g. "emergency housing",
53/// "food relief", "help completing a form". This is the demand side of welfare support.
54#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
55pub struct AssistanceNeed {
56    pub id: String,
57    /// Broad classification of the need, e.g. "housing", "food", "legal", "medical".
58    pub category: String,
59    pub description: String,
60    #[serde(default)]
61    pub urgency: Urgency,
62    pub identified_at_unix: u32,
63    /// High-resolution instant (T71 bridge). Preferred over `identified_at_unix`
64    /// when present; the u32 field is kept for backward-compatible deserialization.
65    #[serde(skip_serializing_if = "Option::is_none", default)]
66    pub identified_at_instant: Option<InstantBridge>,
67}
68
69impl AssistanceNeed {
70    /// Creates a new instance.
71    pub fn new(
72        category: impl Into<String>,
73        description: impl Into<String>,
74        identified_at_unix: u32,
75    ) -> Self {
76        Self {
77            id: Uuid::new_v4().to_string(),
78            category: category.into(),
79            description: description.into(),
80            urgency: Urgency::default(),
81            identified_at_unix,
82            identified_at_instant: Some(InstantBridge::from_coarse(identified_at_unix)),
83        }
84    }
85
86    /// Resolve the identified-at instant, preferring the high-resolution
87    /// `InstantBridge` field when present (T71 bridge).
88    pub fn identified_at(&self) -> InstantBridge {
89        self.identified_at_instant
90            .unwrap_or_else(|| InstantBridge::from_coarse(self.identified_at_unix))
91    }
92}
93
94/// A welfare / benefit / assistance stream the owner is engaged with — a payment program, a
95/// support service, a subsidy. `reference` is the program's own case/claim reference where one
96/// exists. This is the supply side of welfare support.
97#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
98pub struct WelfareStream {
99    pub id: String,
100    pub program_name: String,
101    #[serde(default, skip_serializing_if = "Option::is_none")]
102    pub reference: Option<String>,
103    #[serde(default)]
104    pub status: StreamStatus,
105    pub started_at_unix: u32,
106    /// High-resolution instant (T71 bridge). Preferred over `started_at_unix`
107    /// when present; the u32 field is kept for backward-compatible deserialization.
108    #[serde(skip_serializing_if = "Option::is_none", default)]
109    pub started_at_instant: Option<InstantBridge>,
110}
111
112impl WelfareStream {
113    /// Creates a new instance.
114    pub fn new(program_name: impl Into<String>, started_at_unix: u32) -> Self {
115        Self {
116            id: Uuid::new_v4().to_string(),
117            program_name: program_name.into(),
118            reference: None,
119            status: StreamStatus::default(),
120            started_at_unix,
121            started_at_instant: Some(InstantBridge::from_coarse(started_at_unix)),
122        }
123    }
124
125    /// Resolve the started-at instant, preferring the high-resolution
126    /// `InstantBridge` field when present (T71 bridge).
127    pub fn started_at(&self) -> InstantBridge {
128        self.started_at_instant
129            .unwrap_or_else(|| InstantBridge::from_coarse(self.started_at_unix))
130    }
131}
132
133/// A letter (or equivalent formal communication) received from a government body or agency.
134/// The letter body itself lives out-of-band as a blob (`attachment_blob_hash`); this record is
135/// the indexable envelope over it, flagging whether the owner must act on it.
136#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
137pub struct GovernmentLetter {
138    pub id: String,
139    pub sender: String,
140    pub subject: String,
141    pub received_at_unix: u32,
142    /// High-resolution instant (T71 bridge). Preferred over `received_at_unix`
143    /// when present; the u32 field is kept for backward-compatible deserialization.
144    #[serde(skip_serializing_if = "Option::is_none", default)]
145    pub received_at_instant: Option<InstantBridge>,
146    #[serde(default, skip_serializing_if = "Option::is_none")]
147    pub attachment_blob_hash: Option<String>,
148    #[serde(default)]
149    pub action_required: bool,
150}
151
152impl GovernmentLetter {
153    /// Creates a new instance.
154    pub fn new(
155        sender: impl Into<String>,
156        subject: impl Into<String>,
157        received_at_unix: u32,
158    ) -> Self {
159        Self {
160            id: Uuid::new_v4().to_string(),
161            sender: sender.into(),
162            subject: subject.into(),
163            received_at_unix,
164            received_at_instant: Some(InstantBridge::from_coarse(received_at_unix)),
165            attachment_blob_hash: None,
166            action_required: false,
167        }
168    }
169
170    /// Resolve the received-at instant, preferring the high-resolution
171    /// `InstantBridge` field when present (T71 bridge).
172    pub fn received_at(&self) -> InstantBridge {
173        self.received_at_instant
174            .unwrap_or_else(|| InstantBridge::from_coarse(self.received_at_unix))
175    }
176}
177
178///  record ID.
179pub fn assistance_need_record_id(uuid: &str) -> String {
180    format!("urn:wellfair:assistance_need:{uuid}")
181}
182
183///  record ID.
184pub fn welfare_stream_record_id(uuid: &str) -> String {
185    format!("urn:wellfair:welfare_stream:{uuid}")
186}
187
188///  record ID.
189pub fn government_letter_record_id(uuid: &str) -> String {
190    format!("urn:wellfair:government_letter:{uuid}")
191}
192
193/// Shared Restricted / SelfReported / Asserted envelope for welfare-support records.
194fn self_reported_envelope(
195    id: &str,
196    owner_did: &str,
197    author_did: &str,
198    asserted_unix: u32,
199    valid_time_start_unix: u32,
200    blob_hash: Option<String>,
201) -> RecordEnvelope {
202    RecordEnvelope {
203        id: id.to_string(),
204        owner_did: owner_did.to_string(),
205        author_did: author_did.to_string(),
206        proxy_did: None,
207        epistemic_status: EpistemicStatus::Asserted,
208        evidence_type: EvidenceType::SelfReported,
209        sensitivity: SensitivityClass::Restricted,
210        asserted_time_unix: asserted_unix,
211        asserted_instant: None,
212        valid_time_start_unix: Some(valid_time_start_unix),
213        valid_time_start_instant: None,
214        valid_time_end_unix: None,
215        valid_time_end_instant: None,
216        predecessor_id: None,
217        blob_hash,
218        tombstone: false,
219    }
220}
221
222/// Builds the  envelope.
223pub fn build_assistance_need_envelope(
224    need: &AssistanceNeed,
225    owner_did: &str,
226    author_did: &str,
227    asserted_unix: u32,
228    blob_hash: Option<String>,
229) -> RecordEnvelope {
230    let id = assistance_need_record_id(&need.id);
231    self_reported_envelope(
232        &id,
233        owner_did,
234        author_did,
235        asserted_unix,
236        need.identified_at_unix,
237        blob_hash,
238    )
239}
240
241/// Builds the  envelope.
242pub fn build_welfare_stream_envelope(
243    stream: &WelfareStream,
244    owner_did: &str,
245    author_did: &str,
246    asserted_unix: u32,
247    blob_hash: Option<String>,
248) -> RecordEnvelope {
249    let id = welfare_stream_record_id(&stream.id);
250    self_reported_envelope(
251        &id,
252        owner_did,
253        author_did,
254        asserted_unix,
255        stream.started_at_unix,
256        blob_hash,
257    )
258}
259
260/// Builds the  envelope.
261pub fn build_government_letter_envelope(
262    letter: &GovernmentLetter,
263    owner_did: &str,
264    author_did: &str,
265    asserted_unix: u32,
266) -> RecordEnvelope {
267    let id = government_letter_record_id(&letter.id);
268    // The letter's own attachment is the blob; validity starts when it was received.
269    self_reported_envelope(
270        &id,
271        owner_did,
272        author_did,
273        asserted_unix,
274        letter.received_at_unix,
275        letter.attachment_blob_hash.clone(),
276    )
277}
278
279///  summary.
280pub fn assistance_need_summary(need: &AssistanceNeed) -> String {
281    serde_json::json!({
282        "category": need.category,
283        "description": need.description,
284        "urgency": need.urgency,
285        "identified_at_unix": need.identified_at_unix,
286    })
287    .to_string()
288}
289
290///  summary.
291pub fn welfare_stream_summary(stream: &WelfareStream) -> String {
292    serde_json::json!({
293        "program_name": stream.program_name,
294        "reference": stream.reference,
295        "status": stream.status,
296        "started_at_unix": stream.started_at_unix,
297    })
298    .to_string()
299}
300
301///  summary.
302pub fn government_letter_summary(letter: &GovernmentLetter) -> String {
303    serde_json::json!({
304        "sender": letter.sender,
305        "subject": letter.subject,
306        "received_at_unix": letter.received_at_unix,
307        "attachment_blob_hash": letter.attachment_blob_hash,
308        "action_required": letter.action_required,
309    })
310    .to_string()
311}
312
313#[cfg(test)]
314mod tests {
315    use super::*;
316
317    const OWNER: &str = "did:wf:owner";
318
319    #[test]
320    fn urgency_and_stream_status_defaults() {
321        assert_eq!(Urgency::default(), Urgency::Moderate);
322        assert_eq!(StreamStatus::default(), StreamStatus::Applied);
323
324        // Builders adopt the defaults.
325        let need = AssistanceNeed::new("housing", "Emergency accommodation", 1_700_000_000);
326        assert_eq!(need.urgency, Urgency::Moderate);
327
328        let stream = WelfareStream::new("JobSeeker Payment", 1_700_000_000);
329        assert_eq!(stream.status, StreamStatus::Applied);
330        assert_eq!(stream.reference, None);
331
332        let letter = GovernmentLetter::new("Services Australia", "Claim outcome", 1_700_000_000);
333        assert!(!letter.action_required);
334        assert_eq!(letter.attachment_blob_hash, None);
335    }
336
337    #[test]
338    fn assistance_need_envelope_kind_and_class() {
339        let need = AssistanceNeed::new("food", "Weekly food relief", 1_700_000_100);
340        let env = build_assistance_need_envelope(&need, OWNER, OWNER, 1_700_000_200, None);
341        assert!(env.id.contains(":assistance_need:"));
342        assert_eq!(env.evidence_type, EvidenceType::SelfReported);
343        assert_eq!(env.epistemic_status, EpistemicStatus::Asserted);
344        assert_eq!(env.sensitivity, SensitivityClass::Restricted);
345        // Validity anchors to when the need was identified.
346        assert_eq!(env.valid_time_start_unix, Some(1_700_000_100));
347        assert_eq!(env.asserted_time_unix, 1_700_000_200);
348        assert!(!env.tombstone);
349    }
350
351    #[test]
352    fn welfare_stream_envelope_kind_and_class() {
353        let stream = WelfareStream::new("Disability Support Pension", 1_700_001_000);
354        let env = build_welfare_stream_envelope(
355            &stream,
356            OWNER,
357            OWNER,
358            1_700_001_050,
359            Some("blobref".into()),
360        );
361        assert!(env.id.contains(":welfare_stream:"));
362        assert_eq!(env.evidence_type, EvidenceType::SelfReported);
363        assert_eq!(env.sensitivity, SensitivityClass::Restricted);
364        assert_eq!(env.valid_time_start_unix, Some(1_700_001_000));
365        assert_eq!(env.blob_hash.as_deref(), Some("blobref"));
366    }
367
368    #[test]
369    fn government_letter_envelope_uses_attachment_as_blob() {
370        let mut letter = GovernmentLetter::new("Centrelink", "Appointment notice", 1_700_002_000);
371        letter.attachment_blob_hash = Some("letter-pdf-hash".into());
372        letter.action_required = true;
373        let env = build_government_letter_envelope(&letter, OWNER, OWNER, 1_700_002_010);
374        assert!(env.id.contains(":government_letter:"));
375        assert_eq!(env.evidence_type, EvidenceType::SelfReported);
376        assert_eq!(env.sensitivity, SensitivityClass::Restricted);
377        assert_eq!(env.valid_time_start_unix, Some(1_700_002_000));
378        // The letter's attachment flows through to the envelope blob reference.
379        assert_eq!(env.blob_hash.as_deref(), Some("letter-pdf-hash"));
380    }
381
382    #[test]
383    fn summaries_include_primary_fields() {
384        let mut need = AssistanceNeed::new("legal", "Tenancy dispute advice", 1_700_000_000);
385        need.urgency = Urgency::Critical;
386        let s = assistance_need_summary(&need);
387        assert!(s.contains("legal"));
388        assert!(s.contains("Tenancy dispute advice"));
389        assert!(
390            s.contains("critical"),
391            "urgency must serialize snake_case: {s}"
392        );
393
394        let mut stream = WelfareStream::new("Rent Assistance", 1_700_000_000);
395        stream.reference = Some("CRN-12345".into());
396        stream.status = StreamStatus::Active;
397        let s = welfare_stream_summary(&stream);
398        assert!(s.contains("Rent Assistance"));
399        assert!(s.contains("CRN-12345"));
400        assert!(
401            s.contains("active"),
402            "status must serialize snake_case: {s}"
403        );
404
405        let mut letter = GovernmentLetter::new("ATO", "Tax assessment", 1_700_000_000);
406        letter.action_required = true;
407        let s = government_letter_summary(&letter);
408        assert!(s.contains("ATO"));
409        assert!(s.contains("Tax assessment"));
410        assert!(s.contains("true"), "action_required must be present: {s}");
411    }
412
413    #[test]
414    fn summaries_round_trip_through_serde() {
415        let need = AssistanceNeed::new("medical", "GP appointment help", 1_700_000_000);
416        let json = assistance_need_summary(&need);
417        let v: serde_json::Value = serde_json::from_str(&json).unwrap();
418        assert_eq!(v.get("category").unwrap().as_str().unwrap(), "medical");
419        assert_eq!(v.get("urgency").unwrap().as_str().unwrap(), "moderate");
420    }
421
422    #[test]
423    fn record_ids_carry_unique_kind_segments() {
424        let need = AssistanceNeed::new("housing", "d", 1);
425        let stream = WelfareStream::new("p", 1);
426        let letter = GovernmentLetter::new("s", "subj", 1);
427        assert!(assistance_need_record_id(&need.id).contains(":assistance_need:"));
428        assert!(welfare_stream_record_id(&stream.id).contains(":welfare_stream:"));
429        assert!(government_letter_record_id(&letter.id).contains(":government_letter:"));
430    }
431}