datasynth-core 2.4.0

Core domain models, traits, and distributions for synthetic enterprise data generation
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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
//! Entity registry for centralized master data management.
//!
//! Provides a central registry tracking all master data entities with
//! temporal validity, ensuring referential integrity across transactions.

use chrono::NaiveDate;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};

/// Unique identifier for any entity in the system.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct EntityId {
    /// Type of the entity
    pub entity_type: EntityType,
    /// Unique identifier within the type
    pub id: String,
}

impl EntityId {
    /// Create a new entity ID.
    pub fn new(entity_type: EntityType, id: impl Into<String>) -> Self {
        Self {
            entity_type,
            id: id.into(),
        }
    }

    /// Create a vendor entity ID.
    pub fn vendor(id: impl Into<String>) -> Self {
        Self::new(EntityType::Vendor, id)
    }

    /// Create a customer entity ID.
    pub fn customer(id: impl Into<String>) -> Self {
        Self::new(EntityType::Customer, id)
    }

    /// Create a material entity ID.
    pub fn material(id: impl Into<String>) -> Self {
        Self::new(EntityType::Material, id)
    }

    /// Create a fixed asset entity ID.
    pub fn fixed_asset(id: impl Into<String>) -> Self {
        Self::new(EntityType::FixedAsset, id)
    }

    /// Create an employee entity ID.
    pub fn employee(id: impl Into<String>) -> Self {
        Self::new(EntityType::Employee, id)
    }

    /// Create a cost center entity ID.
    pub fn cost_center(id: impl Into<String>) -> Self {
        Self::new(EntityType::CostCenter, id)
    }

    /// Create a profit center entity ID.
    pub fn profit_center(id: impl Into<String>) -> Self {
        Self::new(EntityType::ProfitCenter, id)
    }

    /// Create a GL account entity ID.
    pub fn gl_account(id: impl Into<String>) -> Self {
        Self::new(EntityType::GlAccount, id)
    }
}

impl std::fmt::Display for EntityId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}:{}", self.entity_type, self.id)
    }
}

/// Types of entities that can be registered.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EntityType {
    /// Vendor/Supplier
    Vendor,
    /// Customer
    Customer,
    /// Material/Product
    Material,
    /// Fixed Asset
    FixedAsset,
    /// Employee
    Employee,
    /// Cost Center
    CostCenter,
    /// Profit Center
    ProfitCenter,
    /// GL Account
    GlAccount,
    /// Company Code
    CompanyCode,
    /// Business Partner (generic)
    BusinessPartner,
    /// Project/WBS Element
    Project,
    /// Internal Order
    InternalOrder,
    /// Company/legal entity
    Company,
    /// Department
    Department,
    /// Contract
    Contract,
    /// Asset (general)
    Asset,
    /// Bank account
    BankAccount,
    /// Purchase order
    PurchaseOrder,
    /// Sales order
    SalesOrder,
    /// Invoice
    Invoice,
    /// Payment
    Payment,
}

impl std::fmt::Display for EntityType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let name = match self {
            Self::Vendor => "VENDOR",
            Self::Customer => "CUSTOMER",
            Self::Material => "MATERIAL",
            Self::FixedAsset => "FIXED_ASSET",
            Self::Employee => "EMPLOYEE",
            Self::CostCenter => "COST_CENTER",
            Self::ProfitCenter => "PROFIT_CENTER",
            Self::GlAccount => "GL_ACCOUNT",
            Self::CompanyCode => "COMPANY_CODE",
            Self::BusinessPartner => "BUSINESS_PARTNER",
            Self::Project => "PROJECT",
            Self::InternalOrder => "INTERNAL_ORDER",
            Self::Company => "COMPANY",
            Self::Department => "DEPARTMENT",
            Self::Contract => "CONTRACT",
            Self::Asset => "ASSET",
            Self::BankAccount => "BANK_ACCOUNT",
            Self::PurchaseOrder => "PURCHASE_ORDER",
            Self::SalesOrder => "SALES_ORDER",
            Self::Invoice => "INVOICE",
            Self::Payment => "PAYMENT",
        };
        write!(f, "{name}")
    }
}

/// Status of an entity at a point in time.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EntityStatus {
    /// Entity is active and can be used in transactions
    #[default]
    Active,
    /// Entity is blocked for new transactions
    Blocked,
    /// Entity is marked for deletion
    MarkedForDeletion,
    /// Entity has been archived
    Archived,
}

/// Record of an entity in the registry.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EntityRecord {
    /// Entity identifier
    pub entity_id: EntityId,
    /// Human-readable name/description
    pub name: String,
    /// Company code this entity belongs to (if applicable)
    pub company_code: Option<String>,
    /// Date the entity was created
    pub created_date: NaiveDate,
    /// Date the entity becomes valid (may differ from created)
    pub valid_from: NaiveDate,
    /// Date the entity is valid until (None = indefinite)
    pub valid_to: Option<NaiveDate>,
    /// Current status
    pub status: EntityStatus,
    /// Date status last changed
    pub status_changed_date: Option<NaiveDate>,
    /// Additional attributes as key-value pairs
    pub attributes: HashMap<String, String>,
}

impl EntityRecord {
    /// Create a new entity record.
    pub fn new(entity_id: EntityId, name: impl Into<String>, created_date: NaiveDate) -> Self {
        Self {
            entity_id,
            name: name.into(),
            company_code: None,
            created_date,
            valid_from: created_date,
            valid_to: None,
            status: EntityStatus::Active,
            status_changed_date: None,
            attributes: HashMap::new(),
        }
    }

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

    /// Set validity period.
    pub fn with_validity(mut self, from: NaiveDate, to: Option<NaiveDate>) -> Self {
        self.valid_from = from;
        self.valid_to = to;
        self
    }

    /// Add an attribute.
    pub fn with_attribute(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.attributes.insert(key.into(), value.into());
        self
    }

    /// Check if the entity is valid on a given date.
    pub fn is_valid_on(&self, date: NaiveDate) -> bool {
        date >= self.valid_from
            && self.valid_to.is_none_or(|to| date <= to)
            && self.status == EntityStatus::Active
    }

    /// Check if the entity can be used in transactions on a given date.
    pub fn can_transact_on(&self, date: NaiveDate) -> bool {
        self.is_valid_on(date) && self.status == EntityStatus::Active
    }
}

/// Event in an entity's lifecycle.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EntityEvent {
    /// Entity this event relates to
    pub entity_id: EntityId,
    /// Type of event
    pub event_type: EntityEventType,
    /// Date the event occurred
    pub event_date: NaiveDate,
    /// Description of the event
    pub description: Option<String>,
}

/// Types of entity lifecycle events.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EntityEventType {
    /// Entity was created
    Created,
    /// Entity was activated
    Activated,
    /// Entity was blocked
    Blocked,
    /// Entity was unblocked
    Unblocked,
    /// Entity was marked for deletion
    MarkedForDeletion,
    /// Entity was archived
    Archived,
    /// Entity validity period changed
    ValidityChanged,
    /// Entity was transferred to another company
    Transferred,
    /// Entity attributes were modified
    Modified,
}

/// Central registry for all master data entities.
///
/// Ensures referential integrity by tracking entity existence and validity
/// over time. All transaction generators should check this registry before
/// using any master data reference.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct EntityRegistry {
    /// All registered entities
    entities: HashMap<EntityId, EntityRecord>,
    /// Index by entity type
    by_type: HashMap<EntityType, Vec<EntityId>>,
    /// Index by company code
    by_company: HashMap<String, Vec<EntityId>>,
    /// Timeline of entity events
    entity_timeline: BTreeMap<NaiveDate, Vec<EntityEvent>>,
}

impl EntityRegistry {
    /// Create a new empty registry.
    pub fn new() -> Self {
        Self::default()
    }

    /// Register a new entity.
    pub fn register(&mut self, record: EntityRecord) {
        let entity_id = record.entity_id.clone();
        let entity_type = entity_id.entity_type;
        let company_code = record.company_code.clone();
        let created_date = record.created_date;

        // Add to main storage
        self.entities.insert(entity_id.clone(), record);

        // Update type index
        self.by_type
            .entry(entity_type)
            .or_default()
            .push(entity_id.clone());

        // Update company index
        if let Some(cc) = company_code {
            self.by_company
                .entry(cc)
                .or_default()
                .push(entity_id.clone());
        }

        // Record creation event
        let event = EntityEvent {
            entity_id,
            event_type: EntityEventType::Created,
            event_date: created_date,
            description: Some("Entity created".to_string()),
        };
        self.entity_timeline
            .entry(created_date)
            .or_default()
            .push(event);
    }

    /// Get an entity by ID.
    pub fn get(&self, entity_id: &EntityId) -> Option<&EntityRecord> {
        self.entities.get(entity_id)
    }

    /// Get a mutable reference to an entity.
    pub fn get_mut(&mut self, entity_id: &EntityId) -> Option<&mut EntityRecord> {
        self.entities.get_mut(entity_id)
    }

    /// Check if an entity exists.
    pub fn exists(&self, entity_id: &EntityId) -> bool {
        self.entities.contains_key(entity_id)
    }

    /// Check if an entity exists and is valid on a given date.
    pub fn is_valid(&self, entity_id: &EntityId, date: NaiveDate) -> bool {
        self.entities
            .get(entity_id)
            .is_some_and(|r| r.is_valid_on(date))
    }

    /// Check if an entity can be used in transactions on a given date.
    pub fn can_transact(&self, entity_id: &EntityId, date: NaiveDate) -> bool {
        self.entities
            .get(entity_id)
            .is_some_and(|r| r.can_transact_on(date))
    }

    /// Get all entities of a given type.
    pub fn get_by_type(&self, entity_type: EntityType) -> Vec<&EntityRecord> {
        self.by_type
            .get(&entity_type)
            .map(|ids| ids.iter().filter_map(|id| self.entities.get(id)).collect())
            .unwrap_or_default()
    }

    /// Get all entities of a given type that are valid on a date.
    pub fn get_valid_by_type(
        &self,
        entity_type: EntityType,
        date: NaiveDate,
    ) -> Vec<&EntityRecord> {
        self.get_by_type(entity_type)
            .into_iter()
            .filter(|r| r.is_valid_on(date))
            .collect()
    }

    /// Get all entities for a company code.
    pub fn get_by_company(&self, company_code: &str) -> Vec<&EntityRecord> {
        self.by_company
            .get(company_code)
            .map(|ids| ids.iter().filter_map(|id| self.entities.get(id)).collect())
            .unwrap_or_default()
    }

    /// Get all entity IDs of a given type.
    pub fn get_ids_by_type(&self, entity_type: EntityType) -> Vec<&EntityId> {
        self.by_type
            .get(&entity_type)
            .map(|ids| ids.iter().collect())
            .unwrap_or_default()
    }

    /// Get count of entities by type.
    pub fn count_by_type(&self, entity_type: EntityType) -> usize {
        self.by_type.get(&entity_type).map_or(0, std::vec::Vec::len)
    }

    /// Get total count of all entities.
    pub fn total_count(&self) -> usize {
        self.entities.len()
    }

    /// Update entity status.
    pub fn update_status(
        &mut self,
        entity_id: &EntityId,
        new_status: EntityStatus,
        date: NaiveDate,
    ) -> bool {
        if let Some(record) = self.entities.get_mut(entity_id) {
            let old_status = record.status;
            record.status = new_status;
            record.status_changed_date = Some(date);

            // Record status change event
            let event_type = match new_status {
                EntityStatus::Active if old_status == EntityStatus::Blocked => {
                    EntityEventType::Unblocked
                }
                EntityStatus::Active => EntityEventType::Activated,
                EntityStatus::Blocked => EntityEventType::Blocked,
                EntityStatus::MarkedForDeletion => EntityEventType::MarkedForDeletion,
                EntityStatus::Archived => EntityEventType::Archived,
            };

            let event = EntityEvent {
                entity_id: entity_id.clone(),
                event_type,
                event_date: date,
                description: Some(format!(
                    "Status changed from {old_status:?} to {new_status:?}"
                )),
            };
            self.entity_timeline.entry(date).or_default().push(event);

            true
        } else {
            false
        }
    }

    /// Block an entity for new transactions.
    pub fn block(&mut self, entity_id: &EntityId, date: NaiveDate) -> bool {
        self.update_status(entity_id, EntityStatus::Blocked, date)
    }

    /// Unblock an entity.
    pub fn unblock(&mut self, entity_id: &EntityId, date: NaiveDate) -> bool {
        self.update_status(entity_id, EntityStatus::Active, date)
    }

    /// Get events that occurred on a specific date.
    pub fn get_events_on(&self, date: NaiveDate) -> &[EntityEvent] {
        self.entity_timeline
            .get(&date)
            .map(std::vec::Vec::as_slice)
            .unwrap_or(&[])
    }

    /// Get events in a date range.
    pub fn get_events_in_range(&self, from: NaiveDate, to: NaiveDate) -> Vec<&EntityEvent> {
        self.entity_timeline
            .range(from..=to)
            .flat_map(|(_, events)| events.iter())
            .collect()
    }

    /// Get the timeline entry dates.
    pub fn timeline_dates(&self) -> impl Iterator<Item = &NaiveDate> {
        self.entity_timeline.keys()
    }

    /// Validate that an entity reference can be used on a transaction date.
    /// Returns an error message if invalid.
    pub fn validate_reference(
        &self,
        entity_id: &EntityId,
        transaction_date: NaiveDate,
    ) -> Result<(), String> {
        match self.entities.get(entity_id) {
            None => Err(format!("Entity {entity_id} does not exist")),
            Some(record) => {
                if transaction_date < record.valid_from {
                    Err(format!(
                        "Entity {} is not valid until {} (transaction date: {})",
                        entity_id, record.valid_from, transaction_date
                    ))
                } else if let Some(valid_to) = record.valid_to {
                    if transaction_date > valid_to {
                        Err(format!(
                            "Entity {entity_id} validity expired on {valid_to} (transaction date: {transaction_date})"
                        ))
                    } else if record.status != EntityStatus::Active {
                        Err(format!(
                            "Entity {} has status {:?} (not active)",
                            entity_id, record.status
                        ))
                    } else {
                        Ok(())
                    }
                } else if record.status != EntityStatus::Active {
                    Err(format!(
                        "Entity {} has status {:?} (not active)",
                        entity_id, record.status
                    ))
                } else {
                    Ok(())
                }
            }
        }
    }

    /// Rebuild all indices (call after deserialization).
    pub fn rebuild_indices(&mut self) {
        self.by_type.clear();
        self.by_company.clear();

        for (entity_id, record) in &self.entities {
            self.by_type
                .entry(entity_id.entity_type)
                .or_default()
                .push(entity_id.clone());

            if let Some(cc) = &record.company_code {
                self.by_company
                    .entry(cc.clone())
                    .or_default()
                    .push(entity_id.clone());
            }
        }
    }

    // === Backward compatibility aliases ===

    /// Alias for `register` - registers a new entity.
    pub fn register_entity(&mut self, record: EntityRecord) {
        self.register(record);
    }

    /// Record an event for an entity.
    pub fn record_event(&mut self, event: EntityEvent) {
        self.entity_timeline
            .entry(event.event_date)
            .or_default()
            .push(event);
    }

    /// Check if an entity is valid on a given date.
    /// Alias for `is_valid`.
    pub fn is_valid_on(&self, entity_id: &EntityId, date: NaiveDate) -> bool {
        self.is_valid(entity_id, date)
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;

    fn test_date(days: i64) -> NaiveDate {
        NaiveDate::from_ymd_opt(2024, 1, 1).unwrap() + chrono::Duration::days(days)
    }

    #[test]
    fn test_entity_registration() {
        let mut registry = EntityRegistry::new();

        let entity_id = EntityId::vendor("V-001");
        let record = EntityRecord::new(entity_id.clone(), "Test Vendor", test_date(0));

        registry.register(record);

        assert!(registry.exists(&entity_id));
        assert_eq!(registry.count_by_type(EntityType::Vendor), 1);
    }

    #[test]
    fn test_entity_validity() {
        let mut registry = EntityRegistry::new();

        let entity_id = EntityId::vendor("V-001");
        let record = EntityRecord::new(entity_id.clone(), "Test Vendor", test_date(10))
            .with_validity(test_date(10), Some(test_date(100)));

        registry.register(record);

        // Before validity period
        assert!(!registry.is_valid(&entity_id, test_date(5)));

        // During validity period
        assert!(registry.is_valid(&entity_id, test_date(50)));

        // After validity period
        assert!(!registry.is_valid(&entity_id, test_date(150)));
    }

    #[test]
    fn test_entity_blocking() {
        let mut registry = EntityRegistry::new();

        let entity_id = EntityId::vendor("V-001");
        let record = EntityRecord::new(entity_id.clone(), "Test Vendor", test_date(0));

        registry.register(record);

        // Initially can transact
        assert!(registry.can_transact(&entity_id, test_date(5)));

        // Block the entity
        registry.block(&entity_id, test_date(10));

        // Cannot transact after blocking
        assert!(!registry.can_transact(&entity_id, test_date(15)));

        // Unblock
        registry.unblock(&entity_id, test_date(20));

        // Can transact again
        assert!(registry.can_transact(&entity_id, test_date(25)));
    }

    #[test]
    fn test_entity_timeline() {
        let mut registry = EntityRegistry::new();

        let entity1 = EntityId::vendor("V-001");
        let entity2 = EntityId::vendor("V-002");

        registry.register(EntityRecord::new(entity1.clone(), "Vendor 1", test_date(0)));
        registry.register(EntityRecord::new(entity2.clone(), "Vendor 2", test_date(5)));

        let events_day0 = registry.get_events_on(test_date(0));
        assert_eq!(events_day0.len(), 1);

        let events_range = registry.get_events_in_range(test_date(0), test_date(10));
        assert_eq!(events_range.len(), 2);
    }

    #[test]
    fn test_company_index() {
        let mut registry = EntityRegistry::new();

        let entity1 = EntityId::vendor("V-001");
        let entity2 = EntityId::vendor("V-002");
        let entity3 = EntityId::customer("C-001");

        registry.register(
            EntityRecord::new(entity1.clone(), "Vendor 1", test_date(0)).with_company_code("1000"),
        );
        registry.register(
            EntityRecord::new(entity2.clone(), "Vendor 2", test_date(0)).with_company_code("2000"),
        );
        registry.register(
            EntityRecord::new(entity3.clone(), "Customer 1", test_date(0))
                .with_company_code("1000"),
        );

        let company_1000_entities = registry.get_by_company("1000");
        assert_eq!(company_1000_entities.len(), 2);
    }

    #[test]
    fn test_validate_reference() {
        let mut registry = EntityRegistry::new();

        let entity_id = EntityId::vendor("V-001");
        let record = EntityRecord::new(entity_id.clone(), "Test Vendor", test_date(10))
            .with_validity(test_date(10), Some(test_date(100)));

        registry.register(record);

        // Before validity
        assert!(registry
            .validate_reference(&entity_id, test_date(5))
            .is_err());

        // During validity
        assert!(registry
            .validate_reference(&entity_id, test_date(50))
            .is_ok());

        // After validity
        assert!(registry
            .validate_reference(&entity_id, test_date(150))
            .is_err());

        // Non-existent entity
        let fake_id = EntityId::vendor("V-999");
        assert!(registry
            .validate_reference(&fake_id, test_date(50))
            .is_err());
    }
}