rvf 0.1.0

Rust implementation of the ValueFlows vocabulary for distributed economic networks
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
//! Commitments - promises for future economic events
//!
//! Commitments represent agreements between agents about future economic
//! activity. They are promises that can be fulfilled by economic events.

use crate::actions::ActionType;
use crate::error::{Error, Result};
use crate::measures::Measure;
use chrono::{DateTime, Utc};

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// Status of a commitment
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub enum CommitmentStatus {
    /// The commitment is pending (not yet due)
    Pending,
    /// The commitment is in progress
    InProgress,
    /// The commitment has been fully fulfilled
    Fulfilled,
    /// The commitment has been partially fulfilled
    PartiallyFulfilled,
    /// The commitment was cancelled
    Cancelled,
    /// The commitment is overdue
    Overdue,
}

impl Default for CommitmentStatus {
    fn default() -> Self {
        CommitmentStatus::Pending
    }
}

/// A commitment - a promise for a future economic event
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct Commitment {
    /// Unique identifier
    pub id: String,
    /// The action promised
    pub action: ActionType,
    /// The providing agent
    pub provider: String,
    /// The receiving agent
    pub receiver: String,
    /// Resource quantity committed
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub resource_quantity: Option<Measure>,
    /// Effort quantity committed
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub effort_quantity: Option<Measure>,
    /// The resource specification
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub resource_conforms_to: Option<String>,
    /// Specific resource committed
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub resource_inventoried_as: Option<String>,
    /// Reference to the process this is input to
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub input_of: Option<String>,
    /// Reference to the process this is output from
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub output_of: Option<String>,
    /// Location where the commitment applies
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub at_location: Option<String>,
    /// Required stage of input resource
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub stage: Option<String>,
    /// Required state of input resource
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub state: Option<String>,
    /// Due date
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub due: Option<DateTime<Utc>>,
    /// Beginning of time window
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub has_beginning: Option<DateTime<Utc>>,
    /// End of time window
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub has_end: Option<DateTime<Utc>>,
    /// Point in time
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub has_point_in_time: Option<DateTime<Utc>>,
    /// Plan this commitment is part of
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub plan: Option<String>,
    /// Agreement this is part of
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub clause_of: Option<String>,
    /// Whether this is finished (no more fulfillment expected)
    pub finished: bool,
    /// Scope (organization context)
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub in_scope_of: Option<String>,
    /// Optional note
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub note: Option<String>,
    /// Current status
    pub status: CommitmentStatus,
    /// Quantity fulfilled so far
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub fulfilled_quantity: Option<Measure>,
    /// When this was created
    pub created_at: DateTime<Utc>,
    /// When this was last updated
    pub updated_at: DateTime<Utc>,
}

impl Commitment {
    /// Create a new commitment builder
    pub fn builder() -> CommitmentBuilder {
        CommitmentBuilder::default()
    }

    /// Check if this commitment is an input to a process
    pub fn is_input(&self) -> bool {
        self.input_of.is_some()
    }

    /// Check if this commitment is an output from a process
    pub fn is_output(&self) -> bool {
        self.output_of.is_some()
    }

    /// Check if the commitment is overdue
    pub fn is_overdue(&self) -> bool {
        if let Some(due) = self.due {
            !self.finished && due < Utc::now()
        } else {
            false
        }
    }

    /// Check if the commitment is fully fulfilled
    pub fn is_fulfilled(&self) -> bool {
        matches!(self.status, CommitmentStatus::Fulfilled)
    }

    /// Get the unfulfilled quantity
    pub fn unfulfilled_quantity(&self) -> Option<Measure> {
        match (&self.resource_quantity, &self.fulfilled_quantity) {
            (Some(committed), Some(fulfilled)) => committed.sub(fulfilled),
            (Some(committed), None) => Some(committed.clone()),
            _ => None,
        }
    }

    /// Record fulfillment of part of this commitment
    pub fn record_fulfillment(&mut self, quantity: &Measure) -> Result<()> {
        if let Some(ref mut fulfilled) = self.fulfilled_quantity {
            if !fulfilled.same_unit(quantity) {
                return Err(Error::UnitMismatch {
                    unit1: fulfilled.unit.to_string(),
                    unit2: quantity.unit.to_string(),
                });
            }
            *fulfilled = fulfilled.add(quantity).unwrap();
        } else {
            self.fulfilled_quantity = Some(quantity.clone());
        }

        // Update status based on fulfillment
        if let Some(ref committed) = self.resource_quantity {
            if let Some(ref fulfilled) = self.fulfilled_quantity {
                if fulfilled.value >= committed.value {
                    self.status = CommitmentStatus::Fulfilled;
                    self.finished = true;
                } else {
                    self.status = CommitmentStatus::PartiallyFulfilled;
                }
            }
        }

        self.updated_at = Utc::now();
        Ok(())
    }

    /// Cancel this commitment
    pub fn cancel(&mut self) {
        self.status = CommitmentStatus::Cancelled;
        self.finished = true;
        self.updated_at = Utc::now();
    }

    /// Mark as in progress
    pub fn start(&mut self) {
        if self.status == CommitmentStatus::Pending {
            self.status = CommitmentStatus::InProgress;
            self.updated_at = Utc::now();
        }
    }
}

/// Builder for Commitment
#[derive(Debug, Default)]
pub struct CommitmentBuilder {
    id: Option<String>,
    action: Option<ActionType>,
    provider: Option<String>,
    receiver: Option<String>,
    resource_quantity: Option<Measure>,
    effort_quantity: Option<Measure>,
    resource_conforms_to: Option<String>,
    resource_inventoried_as: Option<String>,
    input_of: Option<String>,
    output_of: Option<String>,
    at_location: Option<String>,
    stage: Option<String>,
    state: Option<String>,
    due: Option<DateTime<Utc>>,
    has_beginning: Option<DateTime<Utc>>,
    has_end: Option<DateTime<Utc>>,
    has_point_in_time: Option<DateTime<Utc>>,
    plan: Option<String>,
    clause_of: Option<String>,
    in_scope_of: Option<String>,
    note: Option<String>,
}

impl CommitmentBuilder {
    /// Set the ID
    pub fn id(mut self, id: impl Into<String>) -> Self {
        self.id = Some(id.into());
        self
    }

    /// Set the action
    pub fn action(mut self, action: ActionType) -> Self {
        self.action = Some(action);
        self
    }

    /// Set the provider
    pub fn provider(mut self, agent_id: impl Into<String>) -> Self {
        self.provider = Some(agent_id.into());
        self
    }

    /// Set the receiver
    pub fn receiver(mut self, agent_id: impl Into<String>) -> Self {
        self.receiver = Some(agent_id.into());
        self
    }

    /// Set the resource quantity
    pub fn resource_quantity(mut self, quantity: Measure) -> Self {
        self.resource_quantity = Some(quantity);
        self
    }

    /// Set the effort quantity
    pub fn effort_quantity(mut self, quantity: Measure) -> Self {
        self.effort_quantity = Some(quantity);
        self
    }

    /// Set the resource specification
    pub fn resource_conforms_to(mut self, spec_id: impl Into<String>) -> Self {
        self.resource_conforms_to = Some(spec_id.into());
        self
    }

    /// Set the resource
    pub fn resource_inventoried_as(mut self, resource_id: impl Into<String>) -> Self {
        self.resource_inventoried_as = Some(resource_id.into());
        self
    }

    /// Set the process this is input to
    pub fn input_of(mut self, process_id: impl Into<String>) -> Self {
        self.input_of = Some(process_id.into());
        self
    }

    /// Set the process this is output from
    pub fn output_of(mut self, process_id: impl Into<String>) -> Self {
        self.output_of = Some(process_id.into());
        self
    }

    /// Set the location
    pub fn at_location(mut self, location: impl Into<String>) -> Self {
        self.at_location = Some(location.into());
        self
    }

    /// Set the required stage
    pub fn stage(mut self, stage: impl Into<String>) -> Self {
        self.stage = Some(stage.into());
        self
    }

    /// Set the required state
    pub fn state(mut self, state: impl Into<String>) -> Self {
        self.state = Some(state.into());
        self
    }

    /// Set the due date
    pub fn due(mut self, due: DateTime<Utc>) -> Self {
        self.due = Some(due);
        self
    }

    /// Set the beginning time
    pub fn has_beginning(mut self, time: DateTime<Utc>) -> Self {
        self.has_beginning = Some(time);
        self
    }

    /// Set the end time
    pub fn has_end(mut self, time: DateTime<Utc>) -> Self {
        self.has_end = Some(time);
        self
    }

    /// Set the point in time
    pub fn has_point_in_time(mut self, time: DateTime<Utc>) -> Self {
        self.has_point_in_time = Some(time);
        self
    }

    /// Set the plan
    pub fn plan(mut self, plan_id: impl Into<String>) -> Self {
        self.plan = Some(plan_id.into());
        self
    }

    /// Set the agreement
    pub fn clause_of(mut self, agreement_id: impl Into<String>) -> Self {
        self.clause_of = Some(agreement_id.into());
        self
    }

    /// Set the scope
    pub fn in_scope_of(mut self, scope: impl Into<String>) -> Self {
        self.in_scope_of = Some(scope.into());
        self
    }

    /// Set a note
    pub fn note(mut self, note: impl Into<String>) -> Self {
        self.note = Some(note.into());
        self
    }

    /// Build the Commitment
    pub fn build(self) -> Result<Commitment> {
        let id = self.id.ok_or_else(|| Error::missing_field("id"))?;
        let action = self.action.ok_or_else(|| Error::missing_field("action"))?;
        let provider = self
            .provider
            .ok_or_else(|| Error::missing_field("provider"))?;
        let receiver = self
            .receiver
            .ok_or_else(|| Error::missing_field("receiver"))?;

        let now = Utc::now();

        Ok(Commitment {
            id,
            action,
            provider,
            receiver,
            resource_quantity: self.resource_quantity,
            effort_quantity: self.effort_quantity,
            resource_conforms_to: self.resource_conforms_to,
            resource_inventoried_as: self.resource_inventoried_as,
            input_of: self.input_of,
            output_of: self.output_of,
            at_location: self.at_location,
            stage: self.stage,
            state: self.state,
            due: self.due,
            has_beginning: self.has_beginning,
            has_end: self.has_end,
            has_point_in_time: self.has_point_in_time,
            plan: self.plan,
            clause_of: self.clause_of,
            finished: false,
            in_scope_of: self.in_scope_of,
            note: self.note,
            status: CommitmentStatus::Pending,
            fulfilled_quantity: None,
            created_at: now,
            updated_at: now,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::measures::Unit;

    #[test]
    fn test_commitment_builder() {
        let commitment = Commitment::builder()
            .id("commitment-001")
            .action(ActionType::Produce)
            .provider("agent-001")
            .receiver("agent-001")
            .resource_quantity(Measure::new(100, Unit::Kilogram))
            .build()
            .unwrap();

        assert_eq!(commitment.id, "commitment-001");
        assert_eq!(commitment.status, CommitmentStatus::Pending);
        assert!(!commitment.finished);
    }

    #[test]
    fn test_commitment_fulfillment() {
        let mut commitment = Commitment::builder()
            .id("commitment-001")
            .action(ActionType::Produce)
            .provider("agent-001")
            .receiver("agent-001")
            .resource_quantity(Measure::new(100, Unit::Kilogram))
            .build()
            .unwrap();

        commitment
            .record_fulfillment(&Measure::new(50, Unit::Kilogram))
            .unwrap();
        assert_eq!(commitment.status, CommitmentStatus::PartiallyFulfilled);

        commitment
            .record_fulfillment(&Measure::new(50, Unit::Kilogram))
            .unwrap();
        assert_eq!(commitment.status, CommitmentStatus::Fulfilled);
        assert!(commitment.finished);
    }

    #[test]
    fn test_unfulfilled_quantity() {
        let mut commitment = Commitment::builder()
            .id("commitment-001")
            .action(ActionType::Produce)
            .provider("agent-001")
            .receiver("agent-001")
            .resource_quantity(Measure::new(100, Unit::Each))
            .build()
            .unwrap();

        commitment
            .record_fulfillment(&Measure::new(30, Unit::Each))
            .unwrap();

        let unfulfilled = commitment.unfulfilled_quantity().unwrap();
        assert_eq!(unfulfilled.value, 70.into());
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_commitment_serialization() {
        let commitment = Commitment::builder()
            .id("commitment-001")
            .action(ActionType::Transfer)
            .provider("agent-001")
            .receiver("agent-002")
            .resource_quantity(Measure::new(100, Unit::Each))
            .build()
            .unwrap();

        let json = serde_json::to_string(&commitment).unwrap();
        let parsed: Commitment = serde_json::from_str(&json).unwrap();
        assert_eq!(commitment.id, parsed.id);
    }
}