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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
//! Economic Events
//!
//! Economic events represent what actually happened - they are observations
//! of economic activity. Events are immutable records of the past.

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

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

/// An economic event - a record of what actually happened
///
/// Economic events are immutable observations of economic activity.
/// They record the actual flows of resources between agents.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct EconomicEvent {
    /// Unique identifier
    pub id: String,
    /// The action performed
    pub action: ActionType,
    /// The providing agent
    pub provider: String,
    /// The receiving agent
    pub receiver: String,
    /// Resource quantity (for most actions)
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub resource_quantity: Option<Measure>,
    /// Effort quantity (for work/use actions)
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub effort_quantity: Option<Measure>,
    /// The resource being acted upon
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub resource_inventoried_as: Option<String>,
    /// The resource resulting from the action (for transfers, moves)
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub to_resource_inventoried_as: Option<String>,
    /// The resource specification
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub resource_conforms_to: Option<String>,
    /// Reference to the process this is input/output of
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub input_of: Option<String>,
    /// Reference to the process this is output of
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub output_of: Option<String>,
    /// Location of the event
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub at_location: Option<String>,
    /// Destination location (for moves, transfers)
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub to_location: Option<String>,
    /// State to set on the resource
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub state: Option<String>,
    /// When the event occurred
    pub has_point_in_time: DateTime<Utc>,
    /// Beginning of time interval
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub has_beginning: Option<DateTime<Utc>>,
    /// End of time interval
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub has_end: Option<DateTime<Utc>>,
    /// Commitment this fulfills
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub fulfills: Option<String>,
    /// Intent this satisfies
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub satisfies: Option<String>,
    /// Triggered by another event
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub triggered_by: Option<String>,
    /// Agreement reference
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub realized_in: Option<String>,
    /// Reference to event being corrected
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub corrects: Option<String>,
    /// 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>,
    /// When this record was created
    pub created_at: DateTime<Utc>,
}

impl EconomicEvent {
    /// Create a new economic event builder
    pub fn builder() -> EconomicEventBuilder {
        EconomicEventBuilder::default()
    }

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

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

    /// Check if this is a transfer event
    pub fn is_transfer(&self) -> bool {
        self.action.is_transfer()
    }

    /// Check if this is a correction event
    pub fn is_correction(&self) -> bool {
        self.corrects.is_some()
    }

    /// Get the effective quantity (either resource or effort)
    pub fn effective_quantity(&self) -> Option<&Measure> {
        self.resource_quantity
            .as_ref()
            .or(self.effort_quantity.as_ref())
    }
}

/// Builder for EconomicEvent
#[derive(Debug, Default)]
pub struct EconomicEventBuilder {
    id: Option<String>,
    action: Option<ActionType>,
    provider: Option<String>,
    receiver: Option<String>,
    resource_quantity: Option<Measure>,
    effort_quantity: Option<Measure>,
    resource_inventoried_as: Option<String>,
    to_resource_inventoried_as: Option<String>,
    resource_conforms_to: Option<String>,
    input_of: Option<String>,
    output_of: Option<String>,
    at_location: Option<String>,
    to_location: Option<String>,
    state: Option<String>,
    has_point_in_time: Option<DateTime<Utc>>,
    has_beginning: Option<DateTime<Utc>>,
    has_end: Option<DateTime<Utc>>,
    fulfills: Option<String>,
    satisfies: Option<String>,
    triggered_by: Option<String>,
    realized_in: Option<String>,
    corrects: Option<String>,
    in_scope_of: Option<String>,
    note: Option<String>,
}

impl EconomicEventBuilder {
    /// 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 agent
    pub fn provider(mut self, agent_id: impl Into<String>) -> Self {
        self.provider = Some(agent_id.into());
        self
    }

    /// Set the receiver agent
    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 being acted upon
    pub fn resource_inventoried_as(mut self, resource_id: impl Into<String>) -> Self {
        self.resource_inventoried_as = Some(resource_id.into());
        self
    }

    /// Set the destination resource
    pub fn to_resource_inventoried_as(mut self, resource_id: impl Into<String>) -> Self {
        self.to_resource_inventoried_as = Some(resource_id.into());
        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 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 destination location
    pub fn to_location(mut self, location: impl Into<String>) -> Self {
        self.to_location = Some(location.into());
        self
    }

    /// Set the state
    pub fn state(mut self, state: impl Into<String>) -> Self {
        self.state = Some(state.into());
        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 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 commitment this fulfills
    pub fn fulfills(mut self, commitment_id: impl Into<String>) -> Self {
        self.fulfills = Some(commitment_id.into());
        self
    }

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

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

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

    /// Set the event being corrected
    pub fn corrects(mut self, event_id: impl Into<String>) -> Self {
        self.corrects = Some(event_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 EconomicEvent
    pub fn build(self) -> Result<EconomicEvent> {
        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"))?;

        // Validate that at least one quantity is provided
        if self.resource_quantity.is_none() && self.effort_quantity.is_none() {
            return Err(Error::validation(
                "Either resource_quantity or effort_quantity must be provided",
            ));
        }

        let now = Utc::now();
        let has_point_in_time = self.has_point_in_time.unwrap_or(now);

        Ok(EconomicEvent {
            id,
            action,
            provider,
            receiver,
            resource_quantity: self.resource_quantity,
            effort_quantity: self.effort_quantity,
            resource_inventoried_as: self.resource_inventoried_as,
            to_resource_inventoried_as: self.to_resource_inventoried_as,
            resource_conforms_to: self.resource_conforms_to,
            input_of: self.input_of,
            output_of: self.output_of,
            at_location: self.at_location,
            to_location: self.to_location,
            state: self.state,
            has_point_in_time,
            has_beginning: self.has_beginning,
            has_end: self.has_end,
            fulfills: self.fulfills,
            satisfies: self.satisfies,
            triggered_by: self.triggered_by,
            realized_in: self.realized_in,
            corrects: self.corrects,
            in_scope_of: self.in_scope_of,
            note: self.note,
            created_at: now,
        })
    }
}

/// A fulfillment relationship between an event and a commitment
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct Fulfillment {
    /// Unique identifier
    pub id: String,
    /// The commitment being fulfilled
    pub fulfills: String,
    /// The event providing the fulfillment
    pub fulfilled_by: String,
    /// Quantity fulfilled
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub resource_quantity: Option<Measure>,
    /// Effort fulfilled
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub effort_quantity: Option<Measure>,
    /// Optional note
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub note: Option<String>,
}

impl Fulfillment {
    /// Create a new fulfillment
    pub fn new(
        id: impl Into<String>,
        commitment_id: impl Into<String>,
        event_id: impl Into<String>,
    ) -> Self {
        Self {
            id: id.into(),
            fulfills: commitment_id.into(),
            fulfilled_by: event_id.into(),
            resource_quantity: None,
            effort_quantity: None,
            note: None,
        }
    }

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

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

/// A satisfaction relationship between an event and an intent
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct Satisfaction {
    /// Unique identifier
    pub id: String,
    /// The intent being satisfied
    pub satisfies: String,
    /// The event or commitment providing satisfaction
    pub satisfied_by: String,
    /// Quantity satisfied
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub resource_quantity: Option<Measure>,
    /// Effort satisfied
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub effort_quantity: Option<Measure>,
    /// Optional note
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub note: Option<String>,
}

impl Satisfaction {
    /// Create a new satisfaction
    pub fn new(
        id: impl Into<String>,
        intent_id: impl Into<String>,
        satisfied_by: impl Into<String>,
    ) -> Self {
        Self {
            id: id.into(),
            satisfies: intent_id.into(),
            satisfied_by: satisfied_by.into(),
            resource_quantity: None,
            effort_quantity: None,
            note: None,
        }
    }

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

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

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

        assert_eq!(event.id, "event-001");
        assert_eq!(event.action, ActionType::Produce);
        assert!(event.is_output());
        assert!(!event.is_input());
    }

    #[test]
    fn test_transfer_event() {
        let event = EconomicEvent::builder()
            .id("event-002")
            .action(ActionType::Transfer)
            .provider("agent-001")
            .receiver("agent-002")
            .resource_quantity(Measure::new(50, Unit::Each))
            .resource_inventoried_as("resource-001")
            .build()
            .unwrap();

        assert!(event.is_transfer());
    }

    #[test]
    fn test_work_event() {
        let event = EconomicEvent::builder()
            .id("event-003")
            .action(ActionType::Work)
            .provider("agent-001")
            .receiver("agent-002")
            .effort_quantity(Measure::new(8, Unit::Hour))
            .input_of("process-001")
            .build()
            .unwrap();

        assert!(event.is_input());
        assert_eq!(event.effective_quantity().unwrap().value, 8.into());
    }

    #[test]
    fn test_event_missing_quantity() {
        let result = EconomicEvent::builder()
            .id("event-004")
            .action(ActionType::Produce)
            .provider("agent-001")
            .receiver("agent-001")
            .build();

        assert!(result.is_err());
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_event_serialization() {
        let event = EconomicEvent::builder()
            .id("event-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(&event).unwrap();
        let parsed: EconomicEvent = serde_json::from_str(&json).unwrap();
        assert_eq!(event.id, parsed.id);
        assert_eq!(event.action, parsed.action);
    }
}