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
//! Economic Resources and Resource Specifications
//!
//! Economic resources are the things that have value in an economic network.
//! They can be goods, services, digital assets, currencies, or even natural resources.

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

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

/// A specification defining a type of economic resource
///
/// Resource specifications define the "kind" of resource, while EconomicResource
/// represents actual instances of resources.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct ResourceSpecification {
    /// Unique identifier
    pub id: String,
    /// Display name
    pub name: String,
    /// Optional note/description
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub note: Option<String>,
    /// Optional image URL
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub image: Option<String>,
    /// The default unit for this resource type
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub default_unit_of_resource: Option<String>,
    /// The default unit for effort (for work resources)
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub default_unit_of_effort: Option<String>,
    /// Classifications/categories
    #[cfg_attr(feature = "serde", serde(default, skip_serializing_if = "Vec::is_empty"))]
    pub classified_as: Vec<String>,
    /// Whether resources of this type are substitutable
    pub substitutable: bool,
    /// When this was created
    pub created_at: DateTime<Utc>,
    /// When this was last updated
    pub updated_at: DateTime<Utc>,
}

impl ResourceSpecification {
    /// Create a new resource specification builder
    pub fn builder() -> ResourceSpecificationBuilder {
        ResourceSpecificationBuilder::default()
    }
}

/// Builder for ResourceSpecification
#[derive(Debug, Default)]
pub struct ResourceSpecificationBuilder {
    id: Option<String>,
    name: Option<String>,
    note: Option<String>,
    image: Option<String>,
    default_unit_of_resource: Option<String>,
    default_unit_of_effort: Option<String>,
    classified_as: Vec<String>,
    substitutable: bool,
}

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

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

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

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

    /// Set the default unit for resources
    pub fn default_unit_of_resource(mut self, unit: impl Into<String>) -> Self {
        self.default_unit_of_resource = Some(unit.into());
        self
    }

    /// Set the default unit for effort
    pub fn default_unit_of_effort(mut self, unit: impl Into<String>) -> Self {
        self.default_unit_of_effort = Some(unit.into());
        self
    }

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

    /// Set whether resources are substitutable
    pub fn substitutable(mut self, substitutable: bool) -> Self {
        self.substitutable = substitutable;
        self
    }

    /// Build the ResourceSpecification
    pub fn build(self) -> Result<ResourceSpecification> {
        let id = self.id.ok_or_else(|| Error::missing_field("id"))?;
        let name = self.name.ok_or_else(|| Error::missing_field("name"))?;
        let now = Utc::now();

        Ok(ResourceSpecification {
            id,
            name,
            note: self.note,
            image: self.image,
            default_unit_of_resource: self.default_unit_of_resource,
            default_unit_of_effort: self.default_unit_of_effort,
            classified_as: self.classified_as,
            substitutable: self.substitutable,
            created_at: now,
            updated_at: now,
        })
    }
}

/// An actual economic resource
///
/// Economic resources are observable, specific instances of things that have
/// economic value. They conform to a ResourceSpecification.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
pub struct EconomicResource {
    /// Unique identifier
    pub id: String,
    /// Display name for this specific resource
    pub name: String,
    /// The resource specification this conforms to
    pub conforms_to: String,
    /// The primary accountable agent (owner/steward)
    pub primary_accountable: String,
    /// The current custodian (physical possession)
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub custodian: Option<String>,
    /// Accounting quantity (based on rights)
    pub accounting_quantity: Measure,
    /// Onhand quantity (based on custody)
    pub onhand_quantity: Measure,
    /// Current location identifier
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub current_location: Option<String>,
    /// Lot or batch identifier
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub lot: Option<String>,
    /// Tracking identifier (serial number)
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub tracking_identifier: Option<String>,
    /// Reference to containing resource
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub contained_in: Option<String>,
    /// Current stage (process specification)
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub stage: Option<String>,
    /// Current state (e.g., "passed", "failed")
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub state: Option<String>,
    /// Optional note
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub note: Option<String>,
    /// Optional image URL
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub image: Option<String>,
    /// Classifications/categories
    #[cfg_attr(feature = "serde", serde(default, skip_serializing_if = "Vec::is_empty"))]
    pub classified_as: Vec<String>,
    /// When this was created
    pub created_at: DateTime<Utc>,
    /// When this was last updated
    pub updated_at: DateTime<Utc>,
}

impl EconomicResource {
    /// Create a new economic resource builder
    pub fn builder() -> EconomicResourceBuilder {
        EconomicResourceBuilder::default()
    }

    /// Check if the resource has any accounting quantity
    pub fn has_accounting_quantity(&self) -> bool {
        !self.accounting_quantity.is_zero()
    }

    /// Check if the resource has any onhand quantity
    pub fn has_onhand_quantity(&self) -> bool {
        !self.onhand_quantity.is_zero()
    }

    /// Increment the accounting quantity
    pub fn increment_accounting(&mut self, amount: &Measure) -> Result<()> {
        if !self.accounting_quantity.same_unit(amount) {
            return Err(Error::UnitMismatch {
                unit1: self.accounting_quantity.unit.to_string(),
                unit2: amount.unit.to_string(),
            });
        }
        self.accounting_quantity = self.accounting_quantity.add(amount).unwrap();
        self.updated_at = Utc::now();
        Ok(())
    }

    /// Decrement the accounting quantity
    pub fn decrement_accounting(&mut self, amount: &Measure) -> Result<()> {
        if !self.accounting_quantity.same_unit(amount) {
            return Err(Error::UnitMismatch {
                unit1: self.accounting_quantity.unit.to_string(),
                unit2: amount.unit.to_string(),
            });
        }
        self.accounting_quantity = self.accounting_quantity.sub(amount).unwrap();
        self.updated_at = Utc::now();
        Ok(())
    }

    /// Increment the onhand quantity
    pub fn increment_onhand(&mut self, amount: &Measure) -> Result<()> {
        if !self.onhand_quantity.same_unit(amount) {
            return Err(Error::UnitMismatch {
                unit1: self.onhand_quantity.unit.to_string(),
                unit2: amount.unit.to_string(),
            });
        }
        self.onhand_quantity = self.onhand_quantity.add(amount).unwrap();
        self.updated_at = Utc::now();
        Ok(())
    }

    /// Decrement the onhand quantity
    pub fn decrement_onhand(&mut self, amount: &Measure) -> Result<()> {
        if !self.onhand_quantity.same_unit(amount) {
            return Err(Error::UnitMismatch {
                unit1: self.onhand_quantity.unit.to_string(),
                unit2: amount.unit.to_string(),
            });
        }
        self.onhand_quantity = self.onhand_quantity.sub(amount).unwrap();
        self.updated_at = Utc::now();
        Ok(())
    }

    /// Update the current location
    pub fn set_location(&mut self, location: impl Into<String>) {
        self.current_location = Some(location.into());
        self.updated_at = Utc::now();
    }

    /// Update the stage
    pub fn set_stage(&mut self, stage: impl Into<String>) {
        self.stage = Some(stage.into());
        self.updated_at = Utc::now();
    }

    /// Update the state
    pub fn set_state(&mut self, state: impl Into<String>) {
        self.state = Some(state.into());
        self.updated_at = Utc::now();
    }

    /// Set the containing resource
    pub fn set_contained_in(&mut self, container: impl Into<String>) {
        self.contained_in = Some(container.into());
        self.updated_at = Utc::now();
    }

    /// Remove from container
    pub fn remove_from_container(&mut self) {
        self.contained_in = None;
        self.updated_at = Utc::now();
    }

    /// Transfer primary accountable
    pub fn transfer_accountable(&mut self, new_accountable: impl Into<String>) {
        self.primary_accountable = new_accountable.into();
        self.updated_at = Utc::now();
    }

    /// Transfer custody
    pub fn transfer_custody(&mut self, new_custodian: impl Into<String>) {
        self.custodian = Some(new_custodian.into());
        self.updated_at = Utc::now();
    }
}

/// Builder for EconomicResource
#[derive(Debug, Default)]
pub struct EconomicResourceBuilder {
    id: Option<String>,
    name: Option<String>,
    conforms_to: Option<String>,
    primary_accountable: Option<String>,
    custodian: Option<String>,
    accounting_quantity: Option<Measure>,
    onhand_quantity: Option<Measure>,
    current_location: Option<String>,
    lot: Option<String>,
    tracking_identifier: Option<String>,
    contained_in: Option<String>,
    stage: Option<String>,
    state: Option<String>,
    note: Option<String>,
    image: Option<String>,
    classified_as: Vec<String>,
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    /// Set the image URL
    pub fn image(mut self, image: impl Into<String>) -> Self {
        self.image = Some(image.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 EconomicResource
    pub fn build(self) -> Result<EconomicResource> {
        let id = self.id.ok_or_else(|| Error::missing_field("id"))?;
        let name = self.name.ok_or_else(|| Error::missing_field("name"))?;
        let conforms_to = self
            .conforms_to
            .ok_or_else(|| Error::missing_field("conforms_to"))?;
        let primary_accountable = self
            .primary_accountable
            .ok_or_else(|| Error::missing_field("primary_accountable"))?;
        let accounting_quantity = self
            .accounting_quantity
            .ok_or_else(|| Error::missing_field("accounting_quantity"))?;

        // Default onhand to same as accounting if not specified
        let onhand_quantity = self
            .onhand_quantity
            .unwrap_or_else(|| accounting_quantity.clone());

        let now = Utc::now();

        Ok(EconomicResource {
            id,
            name,
            conforms_to,
            primary_accountable,
            custodian: self.custodian,
            accounting_quantity,
            onhand_quantity,
            current_location: self.current_location,
            lot: self.lot,
            tracking_identifier: self.tracking_identifier,
            contained_in: self.contained_in,
            stage: self.stage,
            state: self.state,
            note: self.note,
            image: self.image,
            classified_as: self.classified_as,
            created_at: now,
            updated_at: now,
        })
    }
}

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

    #[test]
    fn test_resource_specification_builder() {
        let spec = ResourceSpecification::builder()
            .id("spec-001")
            .name("Organic Tomatoes")
            .note("Fresh organic tomatoes")
            .substitutable(true)
            .build()
            .unwrap();

        assert_eq!(spec.id, "spec-001");
        assert_eq!(spec.name, "Organic Tomatoes");
        assert!(spec.substitutable);
    }

    #[test]
    fn test_economic_resource_builder() {
        let resource = EconomicResource::builder()
            .id("resource-001")
            .name("Tomato Batch #1")
            .conforms_to("spec-001")
            .primary_accountable("agent-001")
            .accounting_quantity(Measure::new(100, Unit::Kilogram))
            .build()
            .unwrap();

        assert_eq!(resource.id, "resource-001");
        assert_eq!(resource.primary_accountable, "agent-001");
        assert!(resource.has_accounting_quantity());
    }

    #[test]
    fn test_resource_quantity_operations() {
        let mut resource = EconomicResource::builder()
            .id("resource-001")
            .name("Test")
            .conforms_to("spec-001")
            .primary_accountable("agent-001")
            .accounting_quantity(Measure::new(100, Unit::Each))
            .build()
            .unwrap();

        resource
            .increment_accounting(&Measure::new(50, Unit::Each))
            .unwrap();
        assert_eq!(resource.accounting_quantity.value, 150.into());

        resource
            .decrement_accounting(&Measure::new(30, Unit::Each))
            .unwrap();
        assert_eq!(resource.accounting_quantity.value, 120.into());
    }

    #[test]
    fn test_resource_unit_mismatch() {
        let mut resource = EconomicResource::builder()
            .id("resource-001")
            .name("Test")
            .conforms_to("spec-001")
            .primary_accountable("agent-001")
            .accounting_quantity(Measure::new(100, Unit::Each))
            .build()
            .unwrap();

        let result = resource.increment_accounting(&Measure::new(50, Unit::Kilogram));
        assert!(result.is_err());
    }

    #[cfg(feature = "serde")]
    #[test]
    fn test_resource_serialization() {
        let resource = EconomicResource::builder()
            .id("resource-001")
            .name("Test")
            .conforms_to("spec-001")
            .primary_accountable("agent-001")
            .accounting_quantity(Measure::new(100, Unit::Each))
            .build()
            .unwrap();

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