Skip to main content

qualia_client_core/wellfair/api/
mod.rs

1use super::policy::PolicyDecisionService;
2use super::vault::VaultService;
3use ed25519_dalek::SigningKey;
4use wellfare_core::projects::{parse_contribution_summary, Contribution};
5
6const QAPP_SHELL: &str = "wellfair-shell";
7const QAPP_LIFE: &str = "wellfair-life";
8const QAPP_WELLBEING: &str = "wellfair-wellbeing";
9const QAPP_FINANCE: &str = "wellfair-finance";
10const QAPP_PROJECTS: &str = "wellfair-projects";
11const QAPP_CREDENTIALS: &str = "wellfair-credentials";
12const QAPP_CLINICAL: &str = "wellfair-clinical";
13const QAPP_WELFARE: &str = "wellfair-welfare";
14const SOURCE_PERSONAL: &str = "wellfair:personal";
15const SOURCE_LIFE: &str = "wellfair:life";
16const SOURCE_WELLBEING: &str = "wellfair:wellbeing";
17const SOURCE_FINANCE: &str = "wellfair:finance";
18const SOURCE_PROJECTS: &str = "wellfair:projects";
19const SOURCE_CREDENTIALS: &str = "wellfair:credentials";
20const SOURCE_CLINICAL: &str = "wellfair:clinical";
21const SOURCE_WELFARE: &str = "wellfair:welfare";
22const QAPP_COOPERATIVE: &str = "qualia-cooperative";
23const SOURCE_COOPERATIVE: &str = "qualia:cooperative";
24const QAPP_GUARDIANSHIP: &str = "wellfair-guardianship";
25const SOURCE_GUARDIANSHIP: &str = "wellfair:guardianship";
26
27/// Reconstruct a `Contribution` from a stored/transmitted summary JSON losslessly.
28/// The record id (which is the dedup anchor for obligation derivation) is supplied by the
29/// caller — the journal row id locally, or the sync operation's `record_id` for an inbound op.
30fn contribution_from_summary(
31    id: String,
32    summary: &str,
33    occurred_at_unix: u32,
34) -> Option<Contribution> {
35    parse_contribution_summary(id, summary, occurred_at_unix)
36}
37
38/// A per-entry summary of a hypermedia library entry for the UI (drops the raw quins).
39pub(crate) fn library_summary(e: &super::hypermedia_store::LibraryEntry) -> serde_json::Value {
40    serde_json::json!({
41        "asset_uri": e.asset_uri,
42        "media_type": e.media_type,
43        "topics": e.topics,
44        "projects": e.projects,
45        "purposes": e.purposes,
46        "place": e.place,
47        "occurred_at": e.occurred_at,
48        "lat": e.lat,
49        "lon": e.lon,
50        "flags": e.flags,
51        "ingested_unix": e.ingested_unix,
52        "excerpt": e.excerpt,
53        "sensitivity": e.sensitivity,
54        "section": e.section,
55        "commons_visibility": e.commons_visibility,
56        "is_secret": e.is_secret(),
57        "cml_signals": e.cml_signals,
58        "cml_concept_count": e.cml_concept_count,
59        "cml_n3_chars": e.cml_n3.len(),
60        "quin_count": e.quins.len(),
61        "cof_segment_count": e.cof_segment_count,
62        "cof_segment_index": e.cof_segment_index,
63        "cof_profile": e.cof_profile,
64        "cof_html_chars": e.cof_html.len(),
65        "has_cof": !e.cof_html.is_empty(),
66    })
67}
68
69/// Facets a **person** attaches to an asset at ingest — the "software provides the means, the person
70/// authors the meaning" path. These merge *on top of* whatever a processor derived automatically (a photo's
71/// EXIF still wins for its own time/place); they let a plain document be placed on the **timeline** (a date)
72/// or the **map** (coordinates), or collected under a **project** / **purpose** — none of it imposed.
73#[derive(Debug, Clone, Default)]
74pub struct ManualFacets {
75    pub occurred_at: Option<i64>,
76    pub place_label: Option<String>,
77    pub lat: Option<f32>,
78    pub lon: Option<f32>,
79    pub projects: Vec<String>,
80    pub purposes: Vec<String>,
81    /// `public` | `restricted` | `classified` — high sensitivity forces Secret section.
82    pub sensitivity: Option<String>,
83    /// Preferred product section: secret | wellfair | personal | work | tools | software | commons.
84    pub section: Option<String>,
85    /// `none` | `peers` | `commons` — social / micro-commons visibility.
86    pub commons_visibility: Option<String>,
87}
88
89impl ManualFacets {
90    fn is_empty(&self) -> bool {
91        self.occurred_at.is_none()
92            && self.place_label.is_none()
93            && self.lat.is_none()
94            && self.projects.is_empty()
95            && self.purposes.is_empty()
96            && self.sensitivity.is_none()
97            && self.section.is_none()
98            && self.commons_visibility.is_none()
99    }
100}
101
102/// Decode a lowercase/uppercase hex string to bytes (the desktop passes binary assets — a JPEG is not utf-8 —
103/// as hex across the command boundary). Dependency-free; rejects odd length / non-hex.
104fn decode_hex(s: &str) -> Result<Vec<u8>, String> {
105    let s = s.trim();
106    if s.len() % 2 != 0 {
107        return Err("odd-length hex".to_string());
108    }
109    let val = |c: u8| -> Result<u8, String> {
110        match c {
111            b'0'..=b'9' => Ok(c - b'0'),
112            b'a'..=b'f' => Ok(c - b'a' + 10),
113            b'A'..=b'F' => Ok(c - b'A' + 10),
114            _ => Err(format!("non-hex byte {:#x}", c)),
115        }
116    };
117    let b = s.as_bytes();
118    let mut out = Vec::with_capacity(b.len() / 2);
119    let mut i = 0;
120    while i < b.len() {
121        out.push((val(b[i])? << 4) | val(b[i + 1])?);
122        i += 2;
123    }
124    Ok(out)
125}
126
127/// Parse a model string (`"male"` / `"female"`, case-insensitive) into an `AnatomyModel()`.
128pub fn parse_anatomy_model(s: &str) -> Result<wellfare_core::anatomy::AnatomyModel, String> {
129    match s.trim().to_ascii_lowercase().as_str() {
130        "male" | "m" | "xy" => Ok(wellfare_core::anatomy::AnatomyModel::Male),
131        "female" | "f" | "xx" => Ok(wellfare_core::anatomy::AnatomyModel::Female),
132        _ => Err(format!(
133            "unknown anatomy model '{s}' (expected male/female)"
134        )),
135    }
136}
137
138/// Transport-neutral Host API exported for UI and qApps.
139pub struct WebizenHostApi {
140    vault: VaultService,
141    policy: PolicyDecisionService,
142    signing_key: SigningKey,
143    owner_did: String,
144    author_did: String,
145    storage_root: std::path::PathBuf,
146}
147
148mod accountability;
149mod anatomy;
150mod host_core;
151mod library;
152/// Vault-free hypermedia library reads (storage path; no Sanctuary HostApi required).
153pub use library::{
154    library_stats_at, list_library_section_at, query_library_faceted_at, search_library_at,
155    search_library_text_at, search_library_time_at,
156};
157mod agency;
158mod backup_clinical;
159mod coop;
160mod disclosure;
161mod encryption;
162mod guardianship;
163mod pwa;
164mod sanctuary_vault;
165mod sync;
166mod types;
167mod welfare_work;
168
169pub use types::*;
170
171#[cfg(test)]
172mod roundtrip_tests {
173    use super::*;
174    use wellfare_core::projects::{contribution_summary, ContributionPrivacy};
175    use wellfare_core::record::InstantBridge;
176
177    #[test]
178    fn contribution_from_summary_preserves_all_fields() {
179        let mut c = Contribution::new(
180            "proj-1",
181            "did:wf:alice",
182            "Design work",
183            90,
184            25_000,
185            1.5,
186            ContributionPrivacy::Private,
187            1_700_000_000,
188        );
189        c.occurred_at_instant = Some(InstantBridge::unix(1_700_000_000, 42));
190        c.predecessor_id = Some("urn:wellfair:contribution:prev".into());
191
192        let summary = contribution_summary(&c);
193        let restored =
194            contribution_from_summary(c.id.clone(), &summary, 1_700_000_000).expect("restored");
195        assert_eq!(restored, c);
196    }
197}