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
//! Emission generator — derives GHG Protocol Scope 1/2/3 emission records
//! from operational data (energy consumption, vendor spend, headcount).
//!
//! Uses EPA/DEFRA-style emission factors to convert activity data to CO2e tonnes.
use chrono::NaiveDate;
use datasynth_config::schema::EnvironmentalConfig;
use datasynth_core::models::{
    EmissionRecord, EmissionScope, EstimationMethod, ProductionOrder, ProductionOrderStatus,
    Scope3Category,
};
use datasynth_core::utils::seeded_rng;
use rand::prelude::*;
use rand_chacha::ChaCha8Rng;
use rust_decimal::prelude::FromPrimitive;
use rust_decimal::Decimal;
use rust_decimal_macros::dec;

// ---------------------------------------------------------------------------
// Input types — lightweight structs that upstream generators feed in
// ---------------------------------------------------------------------------

/// Energy consumption input for Scope 1 emission derivation.
#[derive(Debug, Clone)]
pub struct EnergyInput {
    pub facility_id: String,
    pub energy_type: EnergyInputType,
    /// Consumption in kWh.
    pub consumption_kwh: Decimal,
    /// Period start date (first of month).
    pub period: NaiveDate,
}

/// Energy input type for emission factor lookup.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EnergyInputType {
    NaturalGas,
    Diesel,
    Coal,
    Electricity,
}

/// Vendor spend input for Scope 3 emission derivation.
#[derive(Debug, Clone)]
pub struct VendorSpendInput {
    pub vendor_id: String,
    pub category: String,
    pub spend: Decimal,
    pub country: String,
}

// ---------------------------------------------------------------------------
// Emission factors (kg CO2e per kWh, per USD, etc.)
// ---------------------------------------------------------------------------

/// Look up an activity-based emission factor (kg CO2e / kWh).
fn emission_factor_kg_per_kwh(energy_type: EnergyInputType) -> Decimal {
    match energy_type {
        // EPA GHG factors (approximate)
        EnergyInputType::NaturalGas => dec!(0.181), // kg CO2e / kWh
        EnergyInputType::Diesel => dec!(0.253),
        EnergyInputType::Coal => dec!(0.341),
        EnergyInputType::Electricity => dec!(0.417), // US grid average
    }
}

/// Look up a spend-based emission factor (kg CO2e / USD).
fn spend_emission_factor(category: &str, country: &str) -> Decimal {
    let base = match category {
        "manufacturing" => dec!(0.80),
        "construction" => dec!(0.65),
        "transportation" => dec!(0.55),
        "chemicals" => dec!(0.70),
        "agriculture" => dec!(0.60),
        "mining" => dec!(0.90),
        "office_supplies" => dec!(0.20),
        "professional_services" => dec!(0.15),
        "technology" => dec!(0.25),
        _ => dec!(0.40), // generic EEIO factor
    };

    // Country adjustment multiplier
    let country_mult = match country {
        "CN" => dec!(1.30),
        "IN" => dec!(1.25),
        "US" => dec!(1.00),
        "DE" | "FR" | "GB" => dec!(0.85),
        "JP" => dec!(0.90),
        _ => dec!(1.00),
    };

    base * country_mult
}

// ---------------------------------------------------------------------------
// EmissionGenerator
// ---------------------------------------------------------------------------

/// Generates [`EmissionRecord`] values from operational data.
///
/// Scope 1: fuel combustion (natural gas, diesel, coal) → activity-based
/// Scope 2: purchased electricity → activity-based
/// Scope 3: vendor spend → spend-based, business travel → average-data
pub struct EmissionGenerator {
    rng: ChaCha8Rng,
    config: EnvironmentalConfig,
    counter: u64,
}

impl EmissionGenerator {
    /// Create a new emission generator.
    pub fn new(config: EnvironmentalConfig, seed: u64) -> Self {
        Self {
            rng: seeded_rng(seed, 0),
            config,
            counter: 0,
        }
    }

    // ----- Scope 1: Direct emissions from fuel combustion -----

    /// Generate Scope 1 emission records from energy consumption data.
    ///
    /// Applies activity-based emission factors to fuel inputs
    /// (natural gas, diesel, coal). Electricity is excluded (Scope 2).
    pub fn generate_scope1(
        &mut self,
        entity_id: &str,
        energy_data: &[EnergyInput],
    ) -> Vec<EmissionRecord> {
        if !self.config.scope1.enabled {
            return Vec::new();
        }

        energy_data
            .iter()
            .filter(|e| e.energy_type != EnergyInputType::Electricity)
            .map(|e| {
                self.counter += 1;
                let factor = emission_factor_kg_per_kwh(e.energy_type);
                let co2e_kg = e.consumption_kwh * factor;
                // Convert kg to tonnes (÷ 1000)
                let co2e_tonnes = (co2e_kg / dec!(1000)).round_dp(4);

                // Small random variance (±5%) to simulate measurement uncertainty
                let variance = dec!(1) + self.random_variance();
                let co2e_tonnes = (co2e_tonnes * variance).round_dp(4);

                EmissionRecord {
                    id: format!("EM-{:06}", self.counter),
                    entity_id: entity_id.to_string(),
                    scope: EmissionScope::Scope1,
                    scope3_category: None,
                    facility_id: Some(e.facility_id.clone()),
                    period: e.period,
                    activity_data: Some(format!("{} kWh", e.consumption_kwh)),
                    activity_unit: Some("kWh".to_string()),
                    emission_factor: Some(factor),
                    co2e_tonnes,
                    estimation_method: EstimationMethod::ActivityBased,
                    source: Some(format!(
                        "EPA GHG factors ({})",
                        self.config.scope1.factor_region
                    )),
                }
            })
            .collect()
    }

    // ----- Scope 2: Indirect emissions from purchased electricity -----

    /// Generate Scope 2 emission records from purchased electricity data.
    pub fn generate_scope2(
        &mut self,
        entity_id: &str,
        energy_data: &[EnergyInput],
    ) -> Vec<EmissionRecord> {
        if !self.config.scope2.enabled {
            return Vec::new();
        }

        energy_data
            .iter()
            .filter(|e| e.energy_type == EnergyInputType::Electricity)
            .map(|e| {
                self.counter += 1;
                let factor = emission_factor_kg_per_kwh(EnergyInputType::Electricity);
                let co2e_kg = e.consumption_kwh * factor;
                let co2e_tonnes = (co2e_kg / dec!(1000)).round_dp(4);

                let variance = dec!(1) + self.random_variance();
                let co2e_tonnes = (co2e_tonnes * variance).round_dp(4);

                EmissionRecord {
                    id: format!("EM-{:06}", self.counter),
                    entity_id: entity_id.to_string(),
                    scope: EmissionScope::Scope2,
                    scope3_category: None,
                    facility_id: Some(e.facility_id.clone()),
                    period: e.period,
                    activity_data: Some(format!("{} kWh", e.consumption_kwh)),
                    activity_unit: Some("kWh".to_string()),
                    emission_factor: Some(factor),
                    co2e_tonnes,
                    estimation_method: EstimationMethod::ActivityBased,
                    source: Some(format!(
                        "Grid average ({})",
                        self.config.scope2.factor_region
                    )),
                }
            })
            .collect()
    }

    // ----- Scope 3: Value chain emissions -----

    /// Generate Scope 3 (Category 1: Purchased Goods) emission records from vendor spend.
    pub fn generate_scope3_purchased_goods(
        &mut self,
        entity_id: &str,
        vendor_spend: &[VendorSpendInput],
        start_date: NaiveDate,
        _end_date: NaiveDate,
    ) -> Vec<EmissionRecord> {
        if !self.config.scope3.enabled {
            return Vec::new();
        }

        vendor_spend
            .iter()
            .map(|vs| {
                self.counter += 1;
                let factor = spend_emission_factor(&vs.category, &vs.country);
                let co2e_kg = vs.spend * factor;
                let co2e_tonnes = (co2e_kg / dec!(1000)).round_dp(4);

                EmissionRecord {
                    id: format!("EM-{:06}", self.counter),
                    entity_id: entity_id.to_string(),
                    scope: EmissionScope::Scope3,
                    scope3_category: Some(Scope3Category::PurchasedGoods),
                    facility_id: None,
                    period: start_date,
                    activity_data: Some(format!("{} USD spend ({})", vs.spend, vs.category)),
                    activity_unit: Some("USD".to_string()),
                    emission_factor: Some(factor),
                    co2e_tonnes,
                    estimation_method: EstimationMethod::SpendBased,
                    source: Some(format!("EEIO factors ({})", vs.country)),
                }
            })
            .collect()
    }

    /// Generate Scope 3 (Category 6: Business Travel) from travel spend.
    pub fn generate_scope3_business_travel(
        &mut self,
        entity_id: &str,
        travel_spend: Decimal,
        period: NaiveDate,
    ) -> Vec<EmissionRecord> {
        if !self.config.scope3.enabled || travel_spend <= Decimal::ZERO {
            return Vec::new();
        }

        self.counter += 1;
        // Average emission factor for business travel: ~0.25 kg CO2e / USD
        let factor = dec!(0.25);
        let co2e_kg = travel_spend * factor;
        let co2e_tonnes = (co2e_kg / dec!(1000)).round_dp(4);

        vec![EmissionRecord {
            id: format!("EM-{:06}", self.counter),
            entity_id: entity_id.to_string(),
            scope: EmissionScope::Scope3,
            scope3_category: Some(Scope3Category::BusinessTravel),
            facility_id: None,
            period,
            activity_data: Some(format!("{travel_spend} USD travel spend")),
            activity_unit: Some("USD".to_string()),
            emission_factor: Some(factor),
            co2e_tonnes,
            estimation_method: EstimationMethod::AverageData,
            source: Some("DEFRA business travel factors".to_string()),
        }]
    }

    /// Generate Scope 3 (Category 7: Employee Commuting) from headcount.
    pub fn generate_scope3_commuting(
        &mut self,
        entity_id: &str,
        headcount: u32,
        period: NaiveDate,
    ) -> Vec<EmissionRecord> {
        if !self.config.scope3.enabled || headcount == 0 {
            return Vec::new();
        }

        self.counter += 1;
        // Average commuting: ~2.5 tonnes CO2e / employee / year → per month
        let annual_per_employee = dec!(2.5);
        let monthly_per_employee = (annual_per_employee / dec!(12)).round_dp(4);
        let co2e_tonnes = (monthly_per_employee * Decimal::from(headcount)).round_dp(4);

        vec![EmissionRecord {
            id: format!("EM-{:06}", self.counter),
            entity_id: entity_id.to_string(),
            scope: EmissionScope::Scope3,
            scope3_category: Some(Scope3Category::EmployeeCommuting),
            facility_id: None,
            period,
            activity_data: Some(format!("{headcount} employees")),
            activity_unit: Some("headcount".to_string()),
            emission_factor: None,
            co2e_tonnes,
            estimation_method: EstimationMethod::AverageData,
            source: Some("EPA commuting average factors".to_string()),
        }]
    }

    // ----- Manufacturing → Energy bridge -----

    /// Convert production order routing operations into energy input records.
    ///
    /// Each order's machine_hours converted to electricity (Scope 2).
    /// Each order's production quantity converted to natural gas consumption (Scope 1).
    ///
    /// Only `Completed` and `Closed` production orders are included.
    pub fn energy_from_production(
        production_orders: &[ProductionOrder],
        kwh_per_machine_hour: Decimal,
        gas_kwh_per_unit: Decimal,
    ) -> Vec<EnergyInput> {
        let mut inputs = Vec::new();

        for order in production_orders {
            // Only include completed / closed orders — in-flight orders
            // have no settled activity data.
            if !matches!(
                order.status,
                ProductionOrderStatus::Completed | ProductionOrderStatus::Closed
            ) {
                continue;
            }

            // Use work_center as the facility identifier; fall back to company_code
            // when work_center is empty.
            let facility_id = if order.work_center.is_empty() {
                order.company_code.clone()
            } else {
                order.work_center.clone()
            };

            // Period: prefer actual_end; fall back to planned_end.
            let period = order.actual_end.unwrap_or(order.planned_end);

            // --- Scope 2: Electricity from machine hours ---
            let machine_hours_dec = Decimal::from_f64(order.machine_hours).unwrap_or(Decimal::ZERO);
            let electricity_kwh = machine_hours_dec * kwh_per_machine_hour;
            if electricity_kwh > Decimal::ZERO {
                inputs.push(EnergyInput {
                    facility_id: facility_id.clone(),
                    energy_type: EnergyInputType::Electricity,
                    consumption_kwh: electricity_kwh,
                    period,
                });
            }

            // --- Scope 1: Natural gas from production quantity ---
            let gas_kwh = order.actual_quantity * gas_kwh_per_unit;
            if gas_kwh > Decimal::ZERO {
                inputs.push(EnergyInput {
                    facility_id,
                    energy_type: EnergyInputType::NaturalGas,
                    consumption_kwh: gas_kwh,
                    period,
                });
            }
        }

        inputs
    }

    /// Small random variance ±5% for measurement uncertainty.
    fn random_variance(&mut self) -> Decimal {
        let v: f64 = self.rng.random_range(-0.05..0.05);
        Decimal::from_f64_retain(v).unwrap_or(Decimal::ZERO)
    }
}

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

    fn d(s: &str) -> NaiveDate {
        NaiveDate::parse_from_str(s, "%Y-%m-%d").unwrap()
    }

    #[test]
    fn test_scope1_emissions_from_energy() {
        let energy_data = vec![EnergyInput {
            facility_id: "F-001".into(),
            energy_type: EnergyInputType::NaturalGas,
            consumption_kwh: dec!(100000),
            period: d("2025-01-01"),
        }];

        let config = EnvironmentalConfig::default();
        let mut gen = EmissionGenerator::new(config, 42);
        let records = gen.generate_scope1("C001", &energy_data);

        assert_eq!(records.len(), 1);
        assert_eq!(records[0].scope, EmissionScope::Scope1);
        assert!(records[0].co2e_tonnes > Decimal::ZERO);
        assert_eq!(
            records[0].estimation_method,
            EstimationMethod::ActivityBased
        );
        assert!(records[0].facility_id.is_some());
    }

    #[test]
    fn test_scope1_excludes_electricity() {
        let energy_data = vec![
            EnergyInput {
                facility_id: "F-001".into(),
                energy_type: EnergyInputType::Electricity,
                consumption_kwh: dec!(500000),
                period: d("2025-01-01"),
            },
            EnergyInput {
                facility_id: "F-001".into(),
                energy_type: EnergyInputType::NaturalGas,
                consumption_kwh: dec!(100000),
                period: d("2025-01-01"),
            },
        ];

        let config = EnvironmentalConfig::default();
        let mut gen = EmissionGenerator::new(config, 42);
        let records = gen.generate_scope1("C001", &energy_data);

        assert_eq!(
            records.len(),
            1,
            "Electricity should be excluded from Scope 1"
        );
        assert_eq!(records[0].scope, EmissionScope::Scope1);
    }

    #[test]
    fn test_scope2_from_electricity() {
        let energy_data = vec![EnergyInput {
            facility_id: "F-001".into(),
            energy_type: EnergyInputType::Electricity,
            consumption_kwh: dec!(200000),
            period: d("2025-01-01"),
        }];

        let config = EnvironmentalConfig::default();
        let mut gen = EmissionGenerator::new(config, 42);
        let records = gen.generate_scope2("C001", &energy_data);

        assert_eq!(records.len(), 1);
        assert_eq!(records[0].scope, EmissionScope::Scope2);
        assert!(records[0].co2e_tonnes > Decimal::ZERO);
    }

    #[test]
    fn test_scope3_from_vendor_spend() {
        let vendor_spend = vec![
            VendorSpendInput {
                vendor_id: "V-001".into(),
                category: "office_supplies".into(),
                spend: dec!(50000),
                country: "US".into(),
            },
            VendorSpendInput {
                vendor_id: "V-002".into(),
                category: "manufacturing".into(),
                spend: dec!(200000),
                country: "CN".into(),
            },
        ];

        let config = EnvironmentalConfig::default();
        let mut gen = EmissionGenerator::new(config, 42);
        let records = gen.generate_scope3_purchased_goods(
            "C001",
            &vendor_spend,
            d("2025-01-01"),
            d("2025-12-31"),
        );

        assert_eq!(records.len(), 2);
        assert!(records.iter().all(|r| r.scope == EmissionScope::Scope3));
        assert!(records
            .iter()
            .all(|r| r.scope3_category == Some(Scope3Category::PurchasedGoods)));
        // Higher spend + manufacturing + China multiplier → higher emissions
        assert!(records[1].co2e_tonnes > records[0].co2e_tonnes);
    }

    #[test]
    fn test_scope3_business_travel() {
        let config = EnvironmentalConfig::default();
        let mut gen = EmissionGenerator::new(config, 42);
        let records = gen.generate_scope3_business_travel("C001", dec!(100000), d("2025-01-01"));

        assert_eq!(records.len(), 1);
        assert_eq!(
            records[0].scope3_category,
            Some(Scope3Category::BusinessTravel)
        );
        assert!(records[0].co2e_tonnes > Decimal::ZERO);
    }

    #[test]
    fn test_scope3_commuting() {
        let config = EnvironmentalConfig::default();
        let mut gen = EmissionGenerator::new(config, 42);
        let records = gen.generate_scope3_commuting("C001", 500, d("2025-06-01"));

        assert_eq!(records.len(), 1);
        assert_eq!(
            records[0].scope3_category,
            Some(Scope3Category::EmployeeCommuting)
        );
        // 500 employees × 2.5 t/yr / 12 ≈ 104 tonnes
        assert!(records[0].co2e_tonnes > dec!(100));
        assert!(records[0].co2e_tonnes < dec!(110));
    }

    #[test]
    fn test_disabled_scope_produces_nothing() {
        let mut config = EnvironmentalConfig::default();
        config.scope1.enabled = false;

        let energy_data = vec![EnergyInput {
            facility_id: "F-001".into(),
            energy_type: EnergyInputType::NaturalGas,
            consumption_kwh: dec!(100000),
            period: d("2025-01-01"),
        }];

        let mut gen = EmissionGenerator::new(config, 42);
        let records = gen.generate_scope1("C001", &energy_data);
        assert!(records.is_empty());
    }

    #[test]
    fn test_deterministic_emissions() {
        let energy_data = vec![EnergyInput {
            facility_id: "F-001".into(),
            energy_type: EnergyInputType::Diesel,
            consumption_kwh: dec!(50000),
            period: d("2025-01-01"),
        }];

        let config = EnvironmentalConfig::default();

        let mut gen1 = EmissionGenerator::new(config.clone(), 42);
        let r1 = gen1.generate_scope1("C001", &energy_data);

        let mut gen2 = EmissionGenerator::new(config, 42);
        let r2 = gen2.generate_scope1("C001", &energy_data);

        assert_eq!(r1.len(), r2.len());
        assert_eq!(r1[0].co2e_tonnes, r2[0].co2e_tonnes);
    }

    #[test]
    fn test_zero_spend_scope3() {
        let config = EnvironmentalConfig::default();
        let mut gen = EmissionGenerator::new(config, 42);
        let records = gen.generate_scope3_business_travel("C001", Decimal::ZERO, d("2025-01-01"));
        assert!(records.is_empty());
    }

    #[test]
    fn test_zero_headcount_commuting() {
        let config = EnvironmentalConfig::default();
        let mut gen = EmissionGenerator::new(config, 42);
        let records = gen.generate_scope3_commuting("C001", 0, d("2025-01-01"));
        assert!(records.is_empty());
    }
}