1use serde::{Deserialize, Serialize};
13use uuid::Uuid;
14
15use crate::record::{
16 EpistemicStatus, EvidenceType, InstantBridge, RecordEnvelope, SensitivityClass,
17};
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
21#[serde(rename_all = "snake_case")]
22pub enum ProjectRole {
23 Steward,
25 Contributor,
27 Observer,
29}
30
31impl Default for ProjectRole {
32 fn default() -> Self {
33 Self::Contributor
34 }
35}
36
37#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
39pub struct Project {
40 pub id: String,
41 pub name: String,
42 pub description: String,
43 #[serde(default)]
45 pub licensing_ontologies: Vec<String>,
46 pub created_at_unix: u32,
47 #[serde(skip_serializing_if = "Option::is_none", default)]
50 pub created_at_instant: Option<InstantBridge>,
51}
52
53impl Project {
54 pub fn new(
56 name: impl Into<String>,
57 description: impl Into<String>,
58 licensing_ontologies: Vec<String>,
59 created_at_unix: u32,
60 ) -> Self {
61 Self {
62 id: Uuid::new_v4().to_string(),
63 name: name.into(),
64 description: description.into(),
65 licensing_ontologies,
66 created_at_unix,
67 created_at_instant: Some(InstantBridge::from_coarse(created_at_unix)),
68 }
69 }
70
71 pub fn created_at(&self) -> InstantBridge {
74 self.created_at_instant
75 .unwrap_or_else(|| InstantBridge::from_coarse(self.created_at_unix))
76 }
77}
78
79#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
81pub struct ProjectMembership {
82 pub id: String,
83 pub project_id: String,
84 pub member_did: String,
85 #[serde(default)]
86 pub role: ProjectRole,
87 pub agreed_at_unix: u32,
88 #[serde(skip_serializing_if = "Option::is_none", default)]
91 pub agreed_at_instant: Option<InstantBridge>,
92}
93
94impl ProjectMembership {
95 pub fn new(
97 project_id: impl Into<String>,
98 member_did: impl Into<String>,
99 role: ProjectRole,
100 agreed_at_unix: u32,
101 ) -> Self {
102 Self {
103 id: Uuid::new_v4().to_string(),
104 project_id: project_id.into(),
105 member_did: member_did.into(),
106 role,
107 agreed_at_unix,
108 agreed_at_instant: Some(InstantBridge::from_coarse(agreed_at_unix)),
109 }
110 }
111
112 pub fn agreed_at(&self) -> InstantBridge {
115 self.agreed_at_instant
116 .unwrap_or_else(|| InstantBridge::from_coarse(self.agreed_at_unix))
117 }
118}
119
120#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
121pub enum ContributionPrivacy {
122 Public,
123 Permissive,
124 Private,
125}
126
127impl Default for ContributionPrivacy {
128 fn default() -> Self {
129 Self::Public
130 }
131}
132
133#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
137pub struct Contribution {
138 pub id: String,
139 pub project_id: String,
140 pub contributor_did: String,
141 pub description: String,
142 pub effort_minutes: u32,
144 #[serde(default)]
146 pub capital_cents: u64,
147 #[serde(default = "default_roi")]
149 pub roi_multiplier: f32,
150 #[serde(default)]
152 pub privacy_level: ContributionPrivacy,
153 pub occurred_at_unix: u32,
154 #[serde(skip_serializing_if = "Option::is_none", default)]
157 pub occurred_at_instant: Option<InstantBridge>,
158 #[serde(default, skip_serializing_if = "Option::is_none")]
160 pub predecessor_id: Option<String>,
161}
162
163fn default_roi() -> f32 {
164 1.0
165}
166
167impl Contribution {
168 #[allow(clippy::too_many_arguments)]
170 pub fn new(
171 project_id: impl Into<String>,
172 contributor_did: impl Into<String>,
173 description: impl Into<String>,
174 effort_minutes: u32,
175 capital_cents: u64,
176 roi_multiplier: f32,
177 privacy_level: ContributionPrivacy,
178 occurred_at_unix: u32,
179 ) -> Self {
180 Self {
181 id: Uuid::new_v4().to_string(),
182 project_id: project_id.into(),
183 contributor_did: contributor_did.into(),
184 description: description.into(),
185 effort_minutes,
186 capital_cents,
187 roi_multiplier,
188 privacy_level,
189 occurred_at_unix,
190 occurred_at_instant: Some(InstantBridge::from_coarse(occurred_at_unix)),
191 predecessor_id: None,
192 }
193 }
194
195 pub fn occurred_at(&self) -> InstantBridge {
198 self.occurred_at_instant
199 .unwrap_or_else(|| InstantBridge::from_coarse(self.occurred_at_unix))
200 }
201
202 pub fn following(mut self, predecessor: &Contribution) -> Self {
204 self.predecessor_id = Some(predecessor.id.clone());
205 self
206 }
207}
208
209#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
210pub struct Obligation {
211 pub project_id: String,
212 pub contributor_did: String,
213 pub total_effort_minutes: u64,
215 #[serde(default)]
217 pub total_capital_cents: u64,
218 #[serde(default)]
220 pub resolved_obligation_score: f64,
221 pub contribution_count: usize,
223}
224
225pub fn project_record_id(uuid: &str) -> String {
231 format!("urn:wellfair:project:{uuid}")
232}
233
234pub fn project_membership_record_id(uuid: &str) -> String {
236 format!("urn:wellfair:project_membership:{uuid}")
237}
238
239pub fn contribution_record_id(uuid: &str) -> String {
241 format!("urn:wellfair:contribution:{uuid}")
242}
243
244pub fn merge_contributions(
251 existing: &[Contribution],
252 incoming: &[Contribution],
253) -> Vec<Contribution> {
254 let mut merged: Vec<Contribution> = Vec::with_capacity(existing.len() + incoming.len());
255 for entry in existing.iter().chain(incoming.iter()) {
256 if !merged.iter().any(|e| e.id == entry.id) {
257 merged.push(entry.clone());
258 }
259 }
260 merged.sort_by(|a, b| {
261 a.occurred_at_unix
262 .cmp(&b.occurred_at_unix)
263 .then_with(|| a.id.cmp(&b.id))
264 });
265 merged
266}
267
268pub fn derive_obligations(contributions: &[Contribution]) -> Vec<Obligation> {
270 let unique = merge_contributions(contributions, &[]);
271 let mut obligations: Vec<Obligation> = Vec::new();
272 for c in &unique {
273 let score = (c.effort_minutes as f64 + c.capital_cents as f64) * c.roi_multiplier as f64;
274 match obligations
275 .iter_mut()
276 .find(|o| o.project_id == c.project_id && o.contributor_did == c.contributor_did)
277 {
278 Some(ob) => {
279 ob.total_effort_minutes += u64::from(c.effort_minutes);
280 ob.total_capital_cents += c.capital_cents;
281 ob.resolved_obligation_score += score;
282 ob.contribution_count += 1;
283 }
284 None => obligations.push(Obligation {
285 project_id: c.project_id.clone(),
286 contributor_did: c.contributor_did.clone(),
287 total_effort_minutes: u64::from(c.effort_minutes),
288 total_capital_cents: c.capital_cents,
289 resolved_obligation_score: score,
290 contribution_count: 1,
291 }),
292 }
293 }
294 obligations.sort_by(|a, b| {
295 a.project_id
296 .cmp(&b.project_id)
297 .then_with(|| a.contributor_did.cmp(&b.contributor_did))
298 });
299 obligations
300}
301
302fn project_envelope(
307 id: &str,
308 owner_did: &str,
309 author_did: &str,
310 asserted_unix: u32,
311 valid_start_unix: u32,
312 valid_start_instant: Option<InstantBridge>,
313 predecessor_id: Option<String>,
314 blob_hash: Option<String>,
315) -> RecordEnvelope {
316 RecordEnvelope {
317 id: id.to_string(),
318 owner_did: owner_did.to_string(),
319 author_did: author_did.to_string(),
320 proxy_did: None,
321 epistemic_status: EpistemicStatus::Asserted,
322 evidence_type: EvidenceType::SelfReported,
323 sensitivity: SensitivityClass::Restricted,
324 asserted_time_unix: asserted_unix,
325 asserted_instant: None,
326 valid_time_start_unix: Some(valid_start_unix),
327 valid_time_start_instant: valid_start_instant,
328 valid_time_end_unix: None,
329 valid_time_end_instant: None,
330 predecessor_id,
331 blob_hash,
332 tombstone: false,
333 }
334}
335
336pub fn build_project_envelope(
338 project: &Project,
339 owner_did: &str,
340 author_did: &str,
341 asserted_unix: u32,
342 blob_hash: Option<String>,
343) -> RecordEnvelope {
344 let id = project_record_id(&project.id);
345 project_envelope(&id, owner_did, author_did, asserted_unix, project.created_at_unix, project.created_at_instant, None, blob_hash)
346}
347
348pub fn build_membership_envelope(
350 membership: &ProjectMembership,
351 owner_did: &str,
352 author_did: &str,
353 asserted_unix: u32,
354 blob_hash: Option<String>,
355) -> RecordEnvelope {
356 let id = project_membership_record_id(&membership.id);
357 project_envelope(&id, owner_did, author_did, asserted_unix, membership.agreed_at_unix, membership.agreed_at_instant, None, blob_hash)
358}
359
360pub fn build_contribution_envelope(
362 contribution: &Contribution,
363 owner_did: &str,
364 author_did: &str,
365 asserted_unix: u32,
366 blob_hash: Option<String>,
367) -> RecordEnvelope {
368 let id = contribution_record_id(&contribution.id);
369 let predecessor_id = contribution.predecessor_id.as_ref().map(|p| contribution_record_id(p));
370 project_envelope(&id, owner_did, author_did, asserted_unix, contribution.occurred_at_unix, contribution.occurred_at_instant, predecessor_id, blob_hash)
371}
372
373pub fn project_summary(project: &Project) -> String {
379 serde_json::json!({
380 "id": project.id,
381 "name": project.name,
382 "description": project.description,
383 "licensing_ontologies": project.licensing_ontologies,
384 "created_at_unix": project.created_at_unix,
385 "created_at_instant": project.created_at_instant,
386 })
387 .to_string()
388}
389
390pub fn membership_summary(membership: &ProjectMembership) -> String {
392 serde_json::json!({
393 "id": membership.id,
394 "project_id": membership.project_id,
395 "member_did": membership.member_did,
396 "role": membership.role,
397 "agreed_at_unix": membership.agreed_at_unix,
398 "agreed_at_instant": membership.agreed_at_instant,
399 })
400 .to_string()
401}
402
403pub fn contribution_summary(contribution: &Contribution) -> String {
406 serde_json::json!({
407 "id": contribution.id,
408 "project_id": contribution.project_id,
409 "contributor_did": contribution.contributor_did,
410 "description": contribution.description,
411 "effort_minutes": contribution.effort_minutes,
412 "capital_cents": contribution.capital_cents,
413 "roi_multiplier": contribution.roi_multiplier,
414 "privacy_level": contribution.privacy_level,
415 "occurred_at_unix": contribution.occurred_at_unix,
416 "occurred_at_instant": contribution.occurred_at_instant,
417 "predecessor_id": contribution.predecessor_id,
418 })
419 .to_string()
420}
421
422pub fn parse_contribution_summary(
424 id: impl Into<String>,
425 summary: &str,
426 fallback_occurred_at_unix: u32,
427) -> Option<Contribution> {
428 let v: serde_json::Value = serde_json::from_str(summary).ok()?;
429 if !v.is_object() {
430 return None;
431 }
432 let id_str = id.into();
433 let resolved_id = if id_str.is_empty() {
434 v.get("id").and_then(|x| x.as_str()).unwrap_or_default().to_string()
435 } else {
436 id_str
437 };
438 let privacy_level = v.get("privacy_level").and_then(|x| serde_json::from_value(x.clone()).ok()).unwrap_or_default();
439 let occurred_at_unix = v.get("occurred_at_unix").and_then(|x| x.as_u64()).map(|t| t as u32).unwrap_or(fallback_occurred_at_unix);
440 let occurred_at_instant = v.get("occurred_at_instant").and_then(|x| serde_json::from_value(x.clone()).ok());
441 Some(Contribution {
442 id: resolved_id,
443 project_id: v.get("project_id").and_then(|x| x.as_str()).unwrap_or_default().to_string(),
444 contributor_did: v.get("contributor_did").and_then(|x| x.as_str()).unwrap_or_default().to_string(),
445 description: v.get("description").and_then(|x| x.as_str()).unwrap_or_default().to_string(),
446 effort_minutes: v.get("effort_minutes").and_then(|x| x.as_u64()).unwrap_or(0) as u32,
447 capital_cents: v.get("capital_cents").and_then(|x| x.as_u64()).unwrap_or(0),
448 roi_multiplier: v.get("roi_multiplier").and_then(|x| x.as_f64()).map(|f| f as f32).unwrap_or(1.0),
449 privacy_level,
450 occurred_at_unix,
451 occurred_at_instant,
452 predecessor_id: v.get("predecessor_id").and_then(|x| x.as_str()).map(|s| s.to_string()),
453 })
454}
455
456#[cfg(test)]
457#[path = "projects_tests.rs"]
458mod tests;