datasynth-generators 2.4.0

50+ data generators covering GL, P2P, O2C, S2C, HR, manufacturing, audit, tax, treasury, and ESG
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
//! Material generator for inventory and product master data.

use chrono::NaiveDate;
use datasynth_core::models::{
    BomComponent, Material, MaterialAccountDetermination, MaterialGroup, MaterialPool,
    MaterialType, UnitOfMeasure, ValuationMethod,
};
use datasynth_core::utils::seeded_rng;
use rand::prelude::*;
use rand_chacha::ChaCha8Rng;
use rust_decimal::Decimal;
use tracing::debug;

/// Configuration for material generation.
#[derive(Debug, Clone)]
pub struct MaterialGeneratorConfig {
    /// Distribution of material types (type, probability)
    pub material_type_distribution: Vec<(MaterialType, f64)>,
    /// Distribution of valuation methods (method, probability)
    pub valuation_method_distribution: Vec<(ValuationMethod, f64)>,
    /// Probability of material having BOM
    pub bom_rate: f64,
    /// Default base unit of measure
    pub default_uom: String,
    /// Gross margin range (min, max) as percentages
    pub gross_margin_range: (f64, f64),
    /// Standard cost range (min, max)
    pub standard_cost_range: (Decimal, Decimal),
}

impl Default for MaterialGeneratorConfig {
    fn default() -> Self {
        Self {
            material_type_distribution: vec![
                (MaterialType::FinishedGood, 0.30),
                (MaterialType::RawMaterial, 0.35),
                (MaterialType::SemiFinished, 0.15),
                (MaterialType::TradingGood, 0.10),
                (MaterialType::OperatingSupplies, 0.05),
                (MaterialType::Packaging, 0.05),
            ],
            valuation_method_distribution: vec![
                (ValuationMethod::StandardCost, 0.60),
                (ValuationMethod::MovingAverage, 0.30),
                (ValuationMethod::Fifo, 0.08),
                (ValuationMethod::Lifo, 0.02),
            ],
            bom_rate: 0.25,
            default_uom: "EA".to_string(),
            gross_margin_range: (0.20, 0.50),
            standard_cost_range: (Decimal::from(10), Decimal::from(10_000)),
        }
    }
}

/// Material description templates by type.
const MATERIAL_DESCRIPTIONS: &[(MaterialType, &[&str])] = &[
    (
        MaterialType::FinishedGood,
        &[
            "Assembled Unit A",
            "Complete Product B",
            "Final Assembly C",
            "Packaged Item D",
            "Ready Product E",
            "Finished Component F",
            "Complete Module G",
            "Final Product H",
        ],
    ),
    (
        MaterialType::RawMaterial,
        &[
            "Steel Plate Grade A",
            "Aluminum Sheet 6061",
            "Copper Wire AWG 12",
            "Plastic Resin ABS",
            "Raw Polymer Mix",
            "Chemical Compound X",
            "Base Material Y",
            "Raw Stock Z",
        ],
    ),
    (
        MaterialType::SemiFinished,
        &[
            "Sub-Assembly Part A",
            "Machined Component B",
            "Intermediate Product C",
            "Partial Assembly D",
            "Semi-Complete Unit E",
            "Work in Progress F",
            "Partially Processed G",
            "Intermediate Module H",
        ],
    ),
    (
        MaterialType::TradingGood,
        &[
            "Resale Item A",
            "Trading Good B",
            "Merchandise C",
            "Distribution Item D",
            "Wholesale Product E",
            "Retail Item F",
            "Trade Good G",
            "Commercial Product H",
        ],
    ),
    (
        MaterialType::OperatingSupplies,
        &[
            "Cleaning Supplies",
            "Office Supplies",
            "Maintenance Supplies",
            "Workshop Consumables",
            "Safety Supplies",
            "Facility Supplies",
            "General Supplies",
            "Operating Materials",
        ],
    ),
    (
        MaterialType::Packaging,
        &[
            "Cardboard Box Large",
            "Plastic Container",
            "Shipping Carton",
            "Protective Wrap",
            "Pallet Unit",
            "Foam Insert",
            "Label Roll",
            "Tape Industrial",
        ],
    ),
];

/// Generator for material master data.
pub struct MaterialGenerator {
    rng: ChaCha8Rng,
    seed: u64,
    config: MaterialGeneratorConfig,
    material_counter: usize,
    created_materials: Vec<String>, // Track for BOM references
    /// Optional country pack for locale-aware generation
    country_pack: Option<datasynth_core::CountryPack>,
}

impl MaterialGenerator {
    /// Create a new material generator.
    pub fn new(seed: u64) -> Self {
        Self::with_config(seed, MaterialGeneratorConfig::default())
    }

    /// Create a new material generator with custom configuration.
    pub fn with_config(seed: u64, config: MaterialGeneratorConfig) -> Self {
        Self {
            rng: seeded_rng(seed, 0),
            seed,
            config,
            material_counter: 0,
            created_materials: Vec::new(),
            country_pack: None,
        }
    }

    /// Set the country pack for locale-aware generation.
    pub fn set_country_pack(&mut self, pack: datasynth_core::CountryPack) {
        self.country_pack = Some(pack);
    }

    /// Set a counter offset so that generated IDs start after a given value.
    ///
    /// This is used when generating materials for multiple companies in parallel
    /// to ensure globally unique IDs. For example, if company 0 generates 100
    /// materials (MAT-000001..MAT-000100), company 1 should set offset=100 so its
    /// materials start at MAT-000101.
    pub fn set_counter_offset(&mut self, offset: usize) {
        self.material_counter = offset;
    }

    /// Generate a single material.
    pub fn generate_material(
        &mut self,
        _company_code: &str,
        _effective_date: NaiveDate,
    ) -> Material {
        self.material_counter += 1;

        let material_id = format!("MAT-{:06}", self.material_counter);
        let material_type = self.select_material_type();
        let description = self.select_description(&material_type);

        let mut material =
            Material::new(material_id.clone(), description.to_string(), material_type);

        // Set material group
        material.material_group = self.select_material_group(&material_type);

        // Set valuation method
        material.valuation_method = self.select_valuation_method();

        // Set costs and prices
        let standard_cost = self.generate_standard_cost();
        material.standard_cost = standard_cost;
        material.purchase_price = standard_cost;
        material.list_price = self.generate_list_price(standard_cost);

        // Set unit of measure
        material.base_uom = if material_type == MaterialType::OperatingSupplies {
            UnitOfMeasure::hour()
        } else {
            UnitOfMeasure::each()
        };

        // Set account determination
        material.account_determination = self.generate_account_determination(&material_type);

        // Set stock and reorder info
        if material_type != MaterialType::OperatingSupplies {
            material.safety_stock = self.generate_safety_stock();
            material.reorder_point = material.safety_stock * Decimal::from(2);
        }

        // Add to created materials for BOM references
        self.created_materials.push(material_id);

        material
    }

    /// Generate a material with specific type.
    pub fn generate_material_of_type(
        &mut self,
        material_type: MaterialType,
        _company_code: &str,
        _effective_date: NaiveDate,
    ) -> Material {
        self.material_counter += 1;

        let material_id = format!("MAT-{:06}", self.material_counter);
        let description = self.select_description(&material_type);

        let mut material =
            Material::new(material_id.clone(), description.to_string(), material_type);

        material.material_group = self.select_material_group(&material_type);
        material.valuation_method = self.select_valuation_method();

        let standard_cost = self.generate_standard_cost();
        material.standard_cost = standard_cost;
        material.purchase_price = standard_cost;
        material.list_price = self.generate_list_price(standard_cost);

        material.base_uom = if material_type == MaterialType::OperatingSupplies {
            UnitOfMeasure::hour()
        } else {
            UnitOfMeasure::each()
        };

        material.account_determination = self.generate_account_determination(&material_type);

        if material_type != MaterialType::OperatingSupplies {
            material.safety_stock = self.generate_safety_stock();
            material.reorder_point = material.safety_stock * Decimal::from(2);
        }

        self.created_materials.push(material_id);

        material
    }

    /// Generate a material with BOM.
    pub fn generate_material_with_bom(
        &mut self,
        company_code: &str,
        effective_date: NaiveDate,
        component_count: usize,
    ) -> Material {
        // Generate component materials first
        let mut components = Vec::new();
        for i in 0..component_count {
            let component_type = if i % 2 == 0 {
                MaterialType::RawMaterial
            } else {
                MaterialType::SemiFinished
            };
            let component =
                self.generate_material_of_type(component_type, company_code, effective_date);

            let quantity = Decimal::from(self.rng.random_range(1..10));
            components.push(BomComponent {
                component_material_id: component.material_id.clone(),
                quantity,
                uom: component.base_uom.code.clone(),
                position: (i + 1) as u16 * 10,
                scrap_percentage: Decimal::ZERO,
                is_optional: false,
                id: None,
                entity_code: None,
                parent_material: None,
                component_description: None,
                level: None,
                is_phantom: false,
            });
        }

        // Generate the finished good with BOM
        let mut material = self.generate_material_of_type(
            MaterialType::FinishedGood,
            company_code,
            effective_date,
        );

        material.bom_components = Some(components);

        material
    }

    /// Generate a material pool with specified count.
    pub fn generate_material_pool(
        &mut self,
        count: usize,
        company_code: &str,
        effective_date: NaiveDate,
    ) -> MaterialPool {
        debug!(count, company_code, %effective_date, "Generating material pool");
        let mut pool = MaterialPool::new();

        for _ in 0..count {
            let material = self.generate_material(company_code, effective_date);
            pool.add_material(material);
        }

        pool
    }

    /// Generate a material pool with BOMs.
    pub fn generate_material_pool_with_bom(
        &mut self,
        count: usize,
        bom_rate: f64,
        company_code: &str,
        effective_date: NaiveDate,
    ) -> MaterialPool {
        let mut pool = MaterialPool::new();

        // First generate raw materials and semi-finished goods
        let raw_count = (count as f64 * 0.4) as usize;
        for _ in 0..raw_count {
            let material = self.generate_material_of_type(
                MaterialType::RawMaterial,
                company_code,
                effective_date,
            );
            pool.add_material(material);
        }

        let semi_count = (count as f64 * 0.2) as usize;
        for _ in 0..semi_count {
            let material = self.generate_material_of_type(
                MaterialType::SemiFinished,
                company_code,
                effective_date,
            );
            pool.add_material(material);
        }

        // Generate finished goods, some with BOM
        let finished_count = count - raw_count - semi_count;
        for _ in 0..finished_count {
            let material =
                if self.rng.random::<f64>() < bom_rate && !self.created_materials.is_empty() {
                    self.generate_material_with_bom_from_existing(company_code, effective_date)
                } else {
                    self.generate_material_of_type(
                        MaterialType::FinishedGood,
                        company_code,
                        effective_date,
                    )
                };
            pool.add_material(material);
        }

        pool
    }

    /// Generate a material with BOM using existing materials.
    fn generate_material_with_bom_from_existing(
        &mut self,
        company_code: &str,
        effective_date: NaiveDate,
    ) -> Material {
        let mut material = self.generate_material_of_type(
            MaterialType::FinishedGood,
            company_code,
            effective_date,
        );

        // Select some existing materials as components
        let component_count = self
            .rng
            .random_range(2..=5)
            .min(self.created_materials.len());
        let mut components = Vec::new();

        for i in 0..component_count {
            if let Some(component_material_id) = self.created_materials.get(i) {
                components.push(BomComponent {
                    component_material_id: component_material_id.clone(),
                    quantity: Decimal::from(self.rng.random_range(1..5)),
                    uom: "EA".to_string(),
                    position: (i + 1) as u16 * 10,
                    scrap_percentage: Decimal::ZERO,
                    is_optional: false,
                    id: None,
                    entity_code: None,
                    parent_material: None,
                    component_description: None,
                    level: None,
                    is_phantom: false,
                });
            }
        }

        if !components.is_empty() {
            material.bom_components = Some(components);
        }

        material
    }

    /// Select material type based on distribution.
    fn select_material_type(&mut self) -> MaterialType {
        let roll: f64 = self.rng.random();
        let mut cumulative = 0.0;

        for (mat_type, prob) in &self.config.material_type_distribution {
            cumulative += prob;
            if roll < cumulative {
                return *mat_type;
            }
        }

        MaterialType::FinishedGood
    }

    /// Select valuation method based on distribution.
    fn select_valuation_method(&mut self) -> ValuationMethod {
        let roll: f64 = self.rng.random();
        let mut cumulative = 0.0;

        for (method, prob) in &self.config.valuation_method_distribution {
            cumulative += prob;
            if roll < cumulative {
                return *method;
            }
        }

        ValuationMethod::StandardCost
    }

    /// Select description for material type.
    fn select_description(&mut self, material_type: &MaterialType) -> &'static str {
        for (mat_type, descriptions) in MATERIAL_DESCRIPTIONS {
            if mat_type == material_type {
                let idx = self.rng.random_range(0..descriptions.len());
                return descriptions[idx];
            }
        }
        "Generic Material"
    }

    /// Select material group for type.
    fn select_material_group(&mut self, material_type: &MaterialType) -> MaterialGroup {
        match material_type {
            MaterialType::FinishedGood => {
                let options = [
                    MaterialGroup::Electronics,
                    MaterialGroup::Mechanical,
                    MaterialGroup::FinishedGoods,
                ];
                options[self.rng.random_range(0..options.len())]
            }
            MaterialType::RawMaterial => {
                let options = [
                    MaterialGroup::Chemicals,
                    MaterialGroup::Chemical,
                    MaterialGroup::Mechanical,
                ];
                options[self.rng.random_range(0..options.len())]
            }
            MaterialType::SemiFinished => {
                let options = [MaterialGroup::Electronics, MaterialGroup::Mechanical];
                options[self.rng.random_range(0..options.len())]
            }
            MaterialType::TradingGood => MaterialGroup::FinishedGoods,
            MaterialType::OperatingSupplies => MaterialGroup::Services,
            MaterialType::Packaging | MaterialType::SparePart => MaterialGroup::Consumables,
            _ => MaterialGroup::Consumables,
        }
    }

    /// Generate standard cost.
    fn generate_standard_cost(&mut self) -> Decimal {
        let min = self.config.standard_cost_range.0;
        let max = self.config.standard_cost_range.1;
        let range = (max - min).to_string().parse::<f64>().unwrap_or(0.0);
        let offset =
            Decimal::from_f64_retain(self.rng.random::<f64>() * range).unwrap_or(Decimal::ZERO);
        (min + offset).round_dp(2)
    }

    /// Generate list price from standard cost.
    fn generate_list_price(&mut self, standard_cost: Decimal) -> Decimal {
        let (min_margin, max_margin) = self.config.gross_margin_range;
        let margin = min_margin + self.rng.random::<f64>() * (max_margin - min_margin);
        let markup = Decimal::from_f64_retain(1.0 / (1.0 - margin)).unwrap_or(Decimal::from(2));
        (standard_cost * markup).round_dp(2)
    }

    /// Generate safety stock.
    fn generate_safety_stock(&mut self) -> Decimal {
        Decimal::from(self.rng.random_range(10..500))
    }

    /// Generate account determination.
    fn generate_account_determination(
        &mut self,
        material_type: &MaterialType,
    ) -> MaterialAccountDetermination {
        match material_type {
            MaterialType::FinishedGood | MaterialType::TradingGood => {
                MaterialAccountDetermination {
                    inventory_account: "140000".to_string(),
                    cogs_account: "500000".to_string(),
                    revenue_account: "400000".to_string(),
                    purchase_expense_account: "500000".to_string(),
                    price_difference_account: "590000".to_string(),
                    gr_ir_account: "290000".to_string(),
                }
            }
            MaterialType::RawMaterial | MaterialType::SemiFinished => {
                MaterialAccountDetermination {
                    inventory_account: "141000".to_string(),
                    cogs_account: "510000".to_string(),
                    revenue_account: "400000".to_string(),
                    purchase_expense_account: "510000".to_string(),
                    price_difference_account: "591000".to_string(),
                    gr_ir_account: "290000".to_string(),
                }
            }
            MaterialType::OperatingSupplies => MaterialAccountDetermination {
                inventory_account: "".to_string(),
                cogs_account: "520000".to_string(),
                revenue_account: "410000".to_string(),
                purchase_expense_account: "520000".to_string(),
                price_difference_account: "".to_string(),
                gr_ir_account: "290000".to_string(),
            },
            _ => MaterialAccountDetermination {
                inventory_account: "145000".to_string(),
                cogs_account: "530000".to_string(),
                revenue_account: "400000".to_string(),
                purchase_expense_account: "530000".to_string(),
                price_difference_account: "595000".to_string(),
                gr_ir_account: "290000".to_string(),
            },
        }
    }

    /// Reset the generator.
    pub fn reset(&mut self) {
        self.rng = seeded_rng(self.seed, 0);
        self.material_counter = 0;
        self.created_materials.clear();
    }
}

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

    #[test]
    fn test_material_generation() {
        let mut gen = MaterialGenerator::new(42);
        let material = gen.generate_material("1000", NaiveDate::from_ymd_opt(2024, 1, 1).unwrap());

        assert!(!material.material_id.is_empty());
        assert!(!material.description.is_empty());
        assert!(material.standard_cost > Decimal::ZERO);
        assert!(material.list_price >= material.standard_cost);
    }

    #[test]
    fn test_material_pool_generation() {
        let mut gen = MaterialGenerator::new(42);
        let pool =
            gen.generate_material_pool(50, "1000", NaiveDate::from_ymd_opt(2024, 1, 1).unwrap());

        assert_eq!(pool.materials.len(), 50);

        // Should have various material types
        let raw_count = pool
            .materials
            .iter()
            .filter(|m| m.material_type == MaterialType::RawMaterial)
            .count();
        let finished_count = pool
            .materials
            .iter()
            .filter(|m| m.material_type == MaterialType::FinishedGood)
            .count();

        assert!(raw_count > 0);
        assert!(finished_count > 0);
    }

    #[test]
    fn test_material_with_bom() {
        let mut gen = MaterialGenerator::new(42);
        let material =
            gen.generate_material_with_bom("1000", NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(), 3);

        assert_eq!(material.material_type, MaterialType::FinishedGood);
        assert!(material.bom_components.is_some());
        assert_eq!(material.bom_components.as_ref().unwrap().len(), 3);
    }

    #[test]
    fn test_material_pool_with_bom() {
        let mut gen = MaterialGenerator::new(42);
        let pool = gen.generate_material_pool_with_bom(
            100,
            0.5,
            "1000",
            NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(),
        );

        assert_eq!(pool.materials.len(), 100);

        // Should have some materials with BOMs
        let bom_count = pool
            .materials
            .iter()
            .filter(|m| m.bom_components.is_some())
            .count();

        assert!(bom_count > 0);
    }

    #[test]
    fn test_deterministic_generation() {
        let mut gen1 = MaterialGenerator::new(42);
        let mut gen2 = MaterialGenerator::new(42);

        let material1 =
            gen1.generate_material("1000", NaiveDate::from_ymd_opt(2024, 1, 1).unwrap());
        let material2 =
            gen2.generate_material("1000", NaiveDate::from_ymd_opt(2024, 1, 1).unwrap());

        assert_eq!(material1.material_id, material2.material_id);
        assert_eq!(material1.description, material2.description);
        assert_eq!(material1.standard_cost, material2.standard_cost);
    }

    #[test]
    fn test_material_margin() {
        let mut gen = MaterialGenerator::new(42);

        for _ in 0..10 {
            let material =
                gen.generate_material("1000", NaiveDate::from_ymd_opt(2024, 1, 1).unwrap());

            // List price should be higher than standard cost (gross margin)
            assert!(
                material.list_price >= material.standard_cost,
                "List price {} should be >= standard cost {}",
                material.list_price,
                material.standard_cost
            );

            // Check margin is within configured range
            let margin = material.gross_margin_percent();
            assert!(
                margin >= Decimal::from(15) && margin <= Decimal::from(55),
                "Margin {} should be within expected range",
                margin
            );
        }
    }
}