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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
//! Intents - offers and requests for economic activity
//!
//! Intents describe potential future events that have not been agreed to.
//! They are used for offers, requests, and matching between agents.

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

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

/// Type of intent
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub enum IntentType {
    /// An offer to provide something
    Offer,
    /// A request to receive something
    Request,
}

impl Default for IntentType {
    fn default() -> Self {
        IntentType::Offer
    }
}

/// Status of an intent
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub enum IntentStatus {
    /// The intent is active and available
    Active,
    /// The intent has been partially satisfied
    PartiallySatisfied,
    /// The intent has been fully satisfied
    Satisfied,
    /// The intent has been cancelled
    Cancelled,
    /// The intent has expired
    Expired,
}

impl Default for IntentStatus {
    fn default() -> Self {
        IntentStatus::Active
    }
}

/// An intent - an offer or request for economic activity
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct Intent {
    /// Unique identifier
    pub id: String,
    /// The action offered/requested
    pub action: ActionType,
    /// The type of intent (offer or request)
    pub intent_type: IntentType,
    /// The providing agent (for offers)
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub provider: Option<String>,
    /// The receiving agent (for requests)
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub receiver: Option<String>,
    /// Resource quantity
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub resource_quantity: Option<Measure>,
    /// Effort quantity
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub effort_quantity: Option<Measure>,
    /// Minimum quantity acceptable
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub minimum_quantity: Option<Measure>,
    /// Available quantity (may differ from resource_quantity)
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub available_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 (if known)
    #[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 intent applies
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub at_location: Option<String>,
    /// Required stage of resource
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub stage: Option<String>,
    /// Required state of 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 availability window
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub has_beginning: Option<DateTime<Utc>>,
    /// End of availability 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>>,
    /// Whether this is finished (no more satisfaction expected)
    pub finished: bool,
    /// Image URL
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub image: 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>,
    /// Classifications for matching
    #[cfg_attr(
        feature = "serde",
        serde(default, skip_serializing_if = "Vec::is_empty")
    )]
    pub classified_as: Vec<String>,
    /// Current status
    pub status: IntentStatus,
    /// Quantity satisfied so far
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub satisfied_quantity: Option<Measure>,
    /// When this was created
    pub created_at: DateTime<Utc>,
    /// When this was last updated
    pub updated_at: DateTime<Utc>,
}

impl Intent {
    /// Create a new intent builder
    pub fn builder() -> IntentBuilder {
        IntentBuilder::default()
    }

    /// Create a new offer builder
    pub fn offer() -> IntentBuilder {
        IntentBuilder::default().intent_type(IntentType::Offer)
    }

    /// Create a new request builder
    pub fn request() -> IntentBuilder {
        IntentBuilder::default().intent_type(IntentType::Request)
    }

    /// Check if this is an offer
    pub fn is_offer(&self) -> bool {
        matches!(self.intent_type, IntentType::Offer)
    }

    /// Check if this is a request
    pub fn is_request(&self) -> bool {
        matches!(self.intent_type, IntentType::Request)
    }

    /// Check if the intent is active
    pub fn is_active(&self) -> bool {
        matches!(
            self.status,
            IntentStatus::Active | IntentStatus::PartiallySatisfied
        )
    }

    /// Check if the intent has expired
    pub fn is_expired(&self) -> bool {
        if let Some(end) = self.has_end {
            end < Utc::now()
        } else {
            false
        }
    }

    /// Get the remaining quantity available
    pub fn remaining_quantity(&self) -> Option<Measure> {
        match (&self.resource_quantity, &self.satisfied_quantity) {
            (Some(total), Some(satisfied)) => total.sub(satisfied),
            (Some(total), None) => Some(total.clone()),
            _ => self.available_quantity.clone(),
        }
    }

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

        // Update status
        if let Some(ref total) = self.resource_quantity {
            if let Some(ref satisfied) = self.satisfied_quantity {
                if satisfied.value >= total.value {
                    self.status = IntentStatus::Satisfied;
                    self.finished = true;
                } else {
                    self.status = IntentStatus::PartiallySatisfied;
                }
            }
        }

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

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

    /// Check if this intent matches another for potential exchange
    pub fn matches(&self, other: &Intent) -> bool {
        // Must be opposite types
        if self.intent_type == other.intent_type {
            return false;
        }

        // Must have matching resource specification
        if self.resource_conforms_to != other.resource_conforms_to {
            return false;
        }

        // Both must be active
        if !self.is_active() || !other.is_active() {
            return false;
        }

        // Check quantity compatibility
        if let (Some(self_qty), Some(other_qty)) =
            (self.remaining_quantity(), other.remaining_quantity())
        {
            if !self_qty.same_unit(&other_qty) {
                return false;
            }
            // At least some quantity must be satisfiable
            if self_qty.is_zero() || other_qty.is_zero() {
                return false;
            }
        }

        true
    }
}

/// Builder for Intent
#[derive(Debug, Default)]
pub struct IntentBuilder {
    id: Option<String>,
    action: Option<ActionType>,
    intent_type: Option<IntentType>,
    provider: Option<String>,
    receiver: Option<String>,
    resource_quantity: Option<Measure>,
    effort_quantity: Option<Measure>,
    minimum_quantity: Option<Measure>,
    available_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>>,
    image: Option<String>,
    in_scope_of: Option<String>,
    note: Option<String>,
    classified_as: Vec<String>,
}

impl IntentBuilder {
    /// 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 intent type
    pub fn intent_type(mut self, intent_type: IntentType) -> Self {
        self.intent_type = Some(intent_type);
        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 minimum quantity
    pub fn minimum_quantity(mut self, quantity: Measure) -> Self {
        self.minimum_quantity = Some(quantity);
        self
    }

    /// Set the available quantity
    pub fn available_quantity(mut self, quantity: Measure) -> Self {
        self.available_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 image URL
    pub fn image(mut self, image: impl Into<String>) -> Self {
        self.image = Some(image.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
    }

    /// Add a classification
    pub fn classified_as(mut self, classification: impl Into<String>) -> Self {
        self.classified_as.push(classification.into());
        self
    }

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

        let now = Utc::now();

        Ok(Intent {
            id,
            action,
            intent_type,
            provider: self.provider,
            receiver: self.receiver,
            resource_quantity: self.resource_quantity,
            effort_quantity: self.effort_quantity,
            minimum_quantity: self.minimum_quantity,
            available_quantity: self.available_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,
            finished: false,
            image: self.image,
            in_scope_of: self.in_scope_of,
            note: self.note,
            classified_as: self.classified_as,
            status: IntentStatus::Active,
            satisfied_quantity: None,
            created_at: now,
            updated_at: now,
        })
    }
}

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

    #[test]
    fn test_offer_builder() {
        let offer = Intent::offer()
            .id("intent-001")
            .action(ActionType::Transfer)
            .provider("agent-001")
            .resource_quantity(Measure::new(100, Unit::Kilogram))
            .resource_conforms_to("spec-001")
            .build()
            .unwrap();

        assert!(offer.is_offer());
        assert!(offer.is_active());
        assert_eq!(offer.provider, Some("agent-001".to_string()));
    }

    #[test]
    fn test_request_builder() {
        let request = Intent::request()
            .id("intent-002")
            .action(ActionType::Transfer)
            .receiver("agent-002")
            .resource_quantity(Measure::new(50, Unit::Kilogram))
            .resource_conforms_to("spec-001")
            .build()
            .unwrap();

        assert!(request.is_request());
        assert_eq!(request.receiver, Some("agent-002".to_string()));
    }

    #[test]
    fn test_intent_matching() {
        let offer = Intent::offer()
            .id("intent-001")
            .action(ActionType::Transfer)
            .provider("agent-001")
            .resource_quantity(Measure::new(100, Unit::Kilogram))
            .resource_conforms_to("spec-001")
            .build()
            .unwrap();

        let request = Intent::request()
            .id("intent-002")
            .action(ActionType::Transfer)
            .receiver("agent-002")
            .resource_quantity(Measure::new(50, Unit::Kilogram))
            .resource_conforms_to("spec-001")
            .build()
            .unwrap();

        assert!(offer.matches(&request));
        assert!(request.matches(&offer));
    }

    #[test]
    fn test_intent_no_match_same_type() {
        let offer1 = Intent::offer()
            .id("intent-001")
            .action(ActionType::Transfer)
            .provider("agent-001")
            .resource_quantity(Measure::new(100, Unit::Kilogram))
            .resource_conforms_to("spec-001")
            .build()
            .unwrap();

        let offer2 = Intent::offer()
            .id("intent-002")
            .action(ActionType::Transfer)
            .provider("agent-002")
            .resource_quantity(Measure::new(50, Unit::Kilogram))
            .resource_conforms_to("spec-001")
            .build()
            .unwrap();

        assert!(!offer1.matches(&offer2));
    }

    #[test]
    fn test_intent_satisfaction() {
        let mut offer = Intent::offer()
            .id("intent-001")
            .action(ActionType::Transfer)
            .provider("agent-001")
            .resource_quantity(Measure::new(100, Unit::Each))
            .build()
            .unwrap();

        offer
            .record_satisfaction(&Measure::new(30, Unit::Each))
            .unwrap();
        assert_eq!(offer.status, IntentStatus::PartiallySatisfied);
        assert_eq!(offer.remaining_quantity().unwrap().value, 70.into());

        offer
            .record_satisfaction(&Measure::new(70, Unit::Each))
            .unwrap();
        assert_eq!(offer.status, IntentStatus::Satisfied);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_intent_serialization() {
        let intent = Intent::offer()
            .id("intent-001")
            .action(ActionType::Transfer)
            .provider("agent-001")
            .resource_quantity(Measure::new(100, Unit::Each))
            .build()
            .unwrap();

        let json = serde_json::to_string(&intent).unwrap();
        let parsed: Intent = serde_json::from_str(&json).unwrap();
        assert_eq!(intent.id, parsed.id);
        assert_eq!(intent.intent_type, parsed.intent_type);
    }
}