datasynth-generators 2.2.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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
//! Counterfactual generation for what-if scenarios and paired examples.
//!
//! This module provides:
//! - Paired normal/anomaly example generation for ML training
//! - Controllable anomaly injection with specific parameters
//! - What-if scenario generation for testing and analysis
//!
//! Counterfactual generation is essential for:
//! - Training robust anomaly detection models
//! - Understanding the impact of specific changes
//! - Testing detection system sensitivity
//! - Generating balanced ML datasets

use chrono::{NaiveDateTime, Utc};
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

use datasynth_core::uuid_factory::{DeterministicUuidFactory, GeneratorType};

use datasynth_core::models::{
    AnomalyCausalReason, AnomalyType, ErrorType, FraudType, InjectionStrategy, JournalEntry,
    JournalEntryLine, LabeledAnomaly, RelationalAnomalyType, StatisticalAnomalyType,
};

/// A counterfactual pair containing both the original and modified versions.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CounterfactualPair {
    /// Unique identifier for this pair.
    pub pair_id: String,

    /// The original (normal) journal entry.
    pub original: JournalEntry,

    /// The modified (anomalous) journal entry.
    pub modified: JournalEntry,

    /// The anomaly label for the modified entry.
    pub anomaly_label: LabeledAnomaly,

    /// Description of what changed.
    pub change_description: String,

    /// The injection strategy applied.
    pub injection_strategy: InjectionStrategy,

    /// Timestamp when the pair was generated.
    pub generated_at: NaiveDateTime,

    /// Additional metadata.
    pub metadata: HashMap<String, String>,
}

impl CounterfactualPair {
    /// Create a new counterfactual pair.
    pub fn new(
        original: JournalEntry,
        modified: JournalEntry,
        anomaly_label: LabeledAnomaly,
        injection_strategy: InjectionStrategy,
        uuid_factory: &DeterministicUuidFactory,
    ) -> Self {
        let pair_id = uuid_factory.next().to_string();
        let change_description = injection_strategy.description();

        Self {
            pair_id,
            original,
            modified,
            anomaly_label,
            change_description,
            injection_strategy,
            generated_at: Utc::now().naive_utc(),
            metadata: HashMap::new(),
        }
    }

    /// Add metadata to the pair.
    pub fn with_metadata(mut self, key: &str, value: &str) -> Self {
        self.metadata.insert(key.to_string(), value.to_string());
        self
    }
}

/// Specification for a counterfactual modification.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum CounterfactualSpec {
    /// Multiply amount by a factor.
    ScaleAmount {
        /// Multiplication factor.
        factor: f64,
    },

    /// Add a fixed amount.
    AddAmount {
        /// Amount to add (can be negative).
        delta: Decimal,
    },

    /// Set amount to a specific value.
    SetAmount {
        /// Target amount.
        target: Decimal,
    },

    /// Shift the posting date.
    ShiftDate {
        /// Days to shift (negative = earlier).
        days: i32,
    },

    /// Change the fiscal period.
    ChangePeriod {
        /// Target fiscal period.
        target_period: u8,
    },

    /// Change the account classification.
    ReclassifyAccount {
        /// New account number.
        new_account: String,
    },

    /// Add a line item.
    AddLineItem {
        /// Account for the new line.
        account: String,
        /// Amount for the new line.
        amount: Decimal,
        /// Is debit (true) or credit (false).
        is_debit: bool,
    },

    /// Remove a line item by index.
    RemoveLineItem {
        /// Index of line to remove.
        line_index: usize,
    },

    /// Split into multiple transactions.
    SplitTransaction {
        /// Number of splits.
        split_count: u32,
    },

    /// Create a round-tripping pattern.
    CreateRoundTrip {
        /// Intermediate entities.
        intermediaries: Vec<String>,
    },

    /// Mark as self-approved.
    SelfApprove,

    /// Inject a specific fraud type.
    InjectFraud {
        /// The fraud type to inject.
        fraud_type: FraudType,
    },

    /// Apply a custom transformation.
    Custom {
        /// Transformation name.
        name: String,
        /// Parameters.
        params: HashMap<String, String>,
    },
}

impl CounterfactualSpec {
    /// Get the anomaly type this spec would produce.
    pub fn to_anomaly_type(&self) -> AnomalyType {
        match self {
            CounterfactualSpec::ScaleAmount { factor } if *factor > 2.0 => {
                AnomalyType::Fraud(FraudType::RevenueManipulation)
            }
            CounterfactualSpec::ScaleAmount { .. } => {
                AnomalyType::Statistical(StatisticalAnomalyType::UnusuallyHighAmount)
            }
            CounterfactualSpec::AddAmount { .. } => {
                AnomalyType::Statistical(StatisticalAnomalyType::UnusuallyHighAmount)
            }
            CounterfactualSpec::SetAmount { .. } => {
                AnomalyType::Statistical(StatisticalAnomalyType::UnusuallyHighAmount)
            }
            CounterfactualSpec::ShiftDate { .. } => AnomalyType::Fraud(FraudType::TimingAnomaly),
            CounterfactualSpec::ChangePeriod { .. } => AnomalyType::Fraud(FraudType::TimingAnomaly),
            CounterfactualSpec::ReclassifyAccount { .. } => {
                AnomalyType::Error(ErrorType::MisclassifiedAccount)
            }
            CounterfactualSpec::AddLineItem { .. } => {
                AnomalyType::Fraud(FraudType::FictitiousEntry)
            }
            CounterfactualSpec::RemoveLineItem { .. } => {
                AnomalyType::Error(ErrorType::MissingField)
            }
            CounterfactualSpec::SplitTransaction { .. } => {
                AnomalyType::Fraud(FraudType::SplitTransaction)
            }
            CounterfactualSpec::CreateRoundTrip { .. } => {
                AnomalyType::Relational(RelationalAnomalyType::CircularTransaction)
            }
            CounterfactualSpec::SelfApprove => AnomalyType::Fraud(FraudType::SelfApproval),
            CounterfactualSpec::InjectFraud { fraud_type } => AnomalyType::Fraud(*fraud_type),
            CounterfactualSpec::Custom { .. } => AnomalyType::Custom("custom".to_string()),
        }
    }

    /// Get a description of this specification.
    pub fn description(&self) -> String {
        match self {
            CounterfactualSpec::ScaleAmount { factor } => {
                format!("Scale amount by {factor:.2}x")
            }
            CounterfactualSpec::AddAmount { delta } => {
                format!("Add {delta} to amount")
            }
            CounterfactualSpec::SetAmount { target } => {
                format!("Set amount to {target}")
            }
            CounterfactualSpec::ShiftDate { days } => {
                if *days < 0 {
                    format!("Backdate by {} days", days.abs())
                } else {
                    format!("Forward-date by {days} days")
                }
            }
            CounterfactualSpec::ChangePeriod { target_period } => {
                format!("Change to period {target_period}")
            }
            CounterfactualSpec::ReclassifyAccount { new_account } => {
                format!("Reclassify to account {new_account}")
            }
            CounterfactualSpec::AddLineItem {
                account,
                amount,
                is_debit,
            } => {
                format!(
                    "Add {} line for {} to account {}",
                    if *is_debit { "debit" } else { "credit" },
                    amount,
                    account
                )
            }
            CounterfactualSpec::RemoveLineItem { line_index } => {
                format!("Remove line item {line_index}")
            }
            CounterfactualSpec::SplitTransaction { split_count } => {
                format!("Split into {split_count} transactions")
            }
            CounterfactualSpec::CreateRoundTrip { intermediaries } => {
                format!(
                    "Create round-trip through {} entities",
                    intermediaries.len()
                )
            }
            CounterfactualSpec::SelfApprove => "Apply self-approval".to_string(),
            CounterfactualSpec::InjectFraud { fraud_type } => {
                format!("Inject {fraud_type:?} fraud")
            }
            CounterfactualSpec::Custom { name, .. } => {
                format!("Apply custom transformation: {name}")
            }
        }
    }
}

/// Generator for counterfactual pairs.
pub struct CounterfactualGenerator {
    /// Seed for reproducibility.
    seed: u64,
    /// Counter for generating unique IDs.
    counter: u64,
    /// Deterministic UUID factory for pair IDs.
    uuid_factory: DeterministicUuidFactory,
}

impl CounterfactualGenerator {
    /// Create a new counterfactual generator.
    pub fn new(seed: u64) -> Self {
        Self {
            seed,
            counter: 0,
            uuid_factory: DeterministicUuidFactory::new(seed, GeneratorType::Anomaly),
        }
    }

    /// Generate a counterfactual pair by applying a specification to an entry.
    pub fn generate(
        &mut self,
        original: &JournalEntry,
        spec: &CounterfactualSpec,
    ) -> CounterfactualPair {
        self.counter += 1;

        // Clone the original to create modified version
        let mut modified = original.clone();

        // Apply the specification to create the modified entry
        let injection_strategy = self.apply_spec(&mut modified, spec, original);

        // Create the anomaly label
        let anomaly_label =
            self.create_anomaly_label(&modified, spec, &injection_strategy, original);

        // Mark the modified entry as fraudulent if the anomaly type is fraud
        if let AnomalyType::Fraud(fraud_type) = spec.to_anomaly_type() {
            modified.header.is_fraud = true;
            modified.header.fraud_type = Some(fraud_type);
        }

        CounterfactualPair::new(
            original.clone(),
            modified,
            anomaly_label,
            injection_strategy,
            &self.uuid_factory,
        )
    }

    /// Generate multiple counterfactual pairs from a single original.
    pub fn generate_batch(
        &mut self,
        original: &JournalEntry,
        specs: &[CounterfactualSpec],
    ) -> Vec<CounterfactualPair> {
        specs
            .iter()
            .map(|spec| self.generate(original, spec))
            .collect()
    }

    /// Apply a specification to a journal entry.
    fn apply_spec(
        &self,
        entry: &mut JournalEntry,
        spec: &CounterfactualSpec,
        original: &JournalEntry,
    ) -> InjectionStrategy {
        match spec {
            CounterfactualSpec::ScaleAmount { factor } => {
                let original_total = original.total_debit();
                for line in &mut entry.lines {
                    if line.debit_amount > Decimal::ZERO {
                        let new_amount = Decimal::from_f64_retain(
                            line.debit_amount.to_f64().unwrap_or(0.0) * factor,
                        )
                        .unwrap_or(line.debit_amount);
                        line.debit_amount = new_amount;
                        line.local_amount = new_amount;
                    }
                    if line.credit_amount > Decimal::ZERO {
                        let new_amount = Decimal::from_f64_retain(
                            line.credit_amount.to_f64().unwrap_or(0.0) * factor,
                        )
                        .unwrap_or(line.credit_amount);
                        line.credit_amount = new_amount;
                        line.local_amount = -new_amount;
                    }
                }
                InjectionStrategy::AmountManipulation {
                    original: original_total,
                    factor: *factor,
                }
            }
            CounterfactualSpec::AddAmount { delta } => {
                // Add delta to first debit line and first credit line to keep balanced
                if !entry.lines.is_empty() {
                    let original_amount = entry.lines[0].debit_amount;
                    if entry.lines[0].debit_amount > Decimal::ZERO {
                        entry.lines[0].debit_amount += delta;
                        entry.lines[0].local_amount += delta;
                    }
                    // Find first credit line and add to it
                    for line in entry.lines.iter_mut().skip(1) {
                        if line.credit_amount > Decimal::ZERO {
                            line.credit_amount += delta;
                            line.local_amount -= delta;
                            break;
                        }
                    }
                    InjectionStrategy::AmountManipulation {
                        original: original_amount,
                        factor: (original_amount + delta).to_f64().unwrap_or(1.0)
                            / original_amount.to_f64().unwrap_or(1.0),
                    }
                } else {
                    InjectionStrategy::Custom {
                        name: "AddAmount".to_string(),
                        parameters: HashMap::new(),
                    }
                }
            }
            CounterfactualSpec::SetAmount { target } => {
                let original_total = original.total_debit();
                if !entry.lines.is_empty() {
                    // Set first debit line
                    if entry.lines[0].debit_amount > Decimal::ZERO {
                        entry.lines[0].debit_amount = *target;
                        entry.lines[0].local_amount = *target;
                    }
                    // Find first credit line and set it
                    for line in entry.lines.iter_mut().skip(1) {
                        if line.credit_amount > Decimal::ZERO {
                            line.credit_amount = *target;
                            line.local_amount = -*target;
                            break;
                        }
                    }
                }
                InjectionStrategy::AmountManipulation {
                    original: original_total,
                    factor: target.to_f64().unwrap_or(1.0) / original_total.to_f64().unwrap_or(1.0),
                }
            }
            CounterfactualSpec::ShiftDate { days } => {
                let original_date = entry.header.posting_date;
                entry.header.posting_date = if *days >= 0 {
                    entry.header.posting_date + chrono::Duration::days(*days as i64)
                } else {
                    entry.header.posting_date - chrono::Duration::days(days.abs() as i64)
                };
                InjectionStrategy::DateShift {
                    days_shifted: *days,
                    original_date,
                }
            }
            CounterfactualSpec::ChangePeriod { target_period } => {
                entry.header.fiscal_period = *target_period;
                InjectionStrategy::TimingManipulation {
                    timing_type: "PeriodChange".to_string(),
                    original_time: None,
                }
            }
            CounterfactualSpec::ReclassifyAccount { new_account } => {
                let old_account = if !entry.lines.is_empty() {
                    let old = entry.lines[0].gl_account.clone();
                    entry.lines[0].gl_account = new_account.clone();
                    entry.lines[0].account_code = new_account.clone();
                    old
                } else {
                    String::new()
                };
                InjectionStrategy::AccountMisclassification {
                    correct_account: old_account,
                    incorrect_account: new_account.clone(),
                }
            }
            CounterfactualSpec::SelfApprove => {
                let user_id = entry.header.created_by.clone();
                entry.header.sod_violation = true;
                InjectionStrategy::SelfApproval { user_id }
            }
            CounterfactualSpec::SplitTransaction { split_count } => {
                let original_amount = original.total_debit();
                let count = (*split_count).max(1);
                let divisor = Decimal::from_f64_retain(count as f64).unwrap_or(Decimal::ONE);

                // Build new lines: for each original line, produce `count` copies
                // with the amount divided by `count`, renumbering sequentially.
                let mut new_lines: Vec<JournalEntryLine> = Vec::new();
                let mut line_number: u32 = 1;
                for orig_line in &original.lines {
                    for _ in 0..count {
                        let mut split_line = orig_line.clone();
                        split_line.line_number = line_number;
                        if split_line.debit_amount > Decimal::ZERO {
                            let split_amt = split_line.debit_amount / divisor;
                            split_line.debit_amount = split_amt;
                            split_line.local_amount = split_amt;
                        }
                        if split_line.credit_amount > Decimal::ZERO {
                            let split_amt = split_line.credit_amount / divisor;
                            split_line.credit_amount = split_amt;
                            split_line.local_amount = -split_amt;
                        }
                        new_lines.push(split_line);
                        line_number += 1;
                    }
                }
                entry.lines = new_lines.into();

                InjectionStrategy::SplitTransaction {
                    original_amount,
                    split_count: *split_count,
                    split_doc_ids: vec![entry.header.document_id.to_string()],
                }
            }
            CounterfactualSpec::CreateRoundTrip { intermediaries } => {
                InjectionStrategy::CircularFlow {
                    entity_chain: intermediaries.clone(),
                }
            }
            CounterfactualSpec::AddLineItem {
                account,
                amount,
                is_debit,
            } => {
                let next_line_number =
                    entry.lines.iter().map(|l| l.line_number).max().unwrap_or(0) + 1;
                let new_line = if *is_debit {
                    JournalEntryLine::debit(
                        entry.header.document_id,
                        next_line_number,
                        account.clone(),
                        *amount,
                    )
                } else {
                    JournalEntryLine::credit(
                        entry.header.document_id,
                        next_line_number,
                        account.clone(),
                        *amount,
                    )
                };
                entry.lines.push(new_line);
                InjectionStrategy::Custom {
                    name: "AddLineItem".to_string(),
                    parameters: HashMap::from([
                        ("account".to_string(), account.clone()),
                        ("amount".to_string(), amount.to_string()),
                        ("is_debit".to_string(), is_debit.to_string()),
                    ]),
                }
            }
            CounterfactualSpec::RemoveLineItem { line_index } => {
                let removed_account = if *line_index < entry.lines.len() {
                    let removed = entry.lines.remove(*line_index);
                    removed.gl_account
                } else {
                    String::from("(index out of bounds)")
                };
                InjectionStrategy::Custom {
                    name: "RemoveLineItem".to_string(),
                    parameters: HashMap::from([
                        ("line_index".to_string(), line_index.to_string()),
                        ("removed_account".to_string(), removed_account),
                    ]),
                }
            }
            _ => InjectionStrategy::Custom {
                name: spec.description(),
                parameters: HashMap::new(),
            },
        }
    }

    /// Create an anomaly label for the modified entry.
    fn create_anomaly_label(
        &self,
        modified: &JournalEntry,
        spec: &CounterfactualSpec,
        strategy: &InjectionStrategy,
        original: &JournalEntry,
    ) -> LabeledAnomaly {
        let anomaly_id = format!("CF-{}-{}", self.seed, self.counter);
        let anomaly_type = spec.to_anomaly_type();

        LabeledAnomaly {
            anomaly_id,
            anomaly_type: anomaly_type.clone(),
            document_id: modified.header.document_id.to_string(),
            document_type: "JournalEntry".to_string(),
            company_code: modified.header.company_code.clone(),
            anomaly_date: modified.header.posting_date,
            detection_timestamp: Utc::now().naive_utc(),
            confidence: 1.0, // Counterfactuals are known anomalies
            severity: anomaly_type.severity(),
            description: spec.description(),
            related_entities: vec![original.header.document_id.to_string()],
            monetary_impact: Some(modified.total_debit()),
            metadata: HashMap::new(),
            is_injected: true,
            injection_strategy: Some(strategy.description()),
            cluster_id: None,
            original_document_hash: Some(format!("{:x}", hash_entry(original))),
            causal_reason: Some(AnomalyCausalReason::MLTrainingBalance {
                target_class: "counterfactual".to_string(),
            }),
            structured_strategy: Some(strategy.clone()),
            parent_anomaly_id: None,
            child_anomaly_ids: vec![],
            scenario_id: None,
            run_id: None,
            generation_seed: Some(self.seed),
        }
    }
}

/// Simple hash function for journal entries (for provenance tracking).
fn hash_entry(entry: &JournalEntry) -> u64 {
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};

    let mut hasher = DefaultHasher::new();
    entry.header.document_id.hash(&mut hasher);
    entry.header.company_code.hash(&mut hasher);
    entry.header.posting_date.hash(&mut hasher);
    entry.lines.len().hash(&mut hasher);
    hasher.finish()
}

/// Configuration for batch counterfactual generation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CounterfactualConfig {
    /// Seed for reproducibility.
    pub seed: u64,
    /// Number of counterfactual variants per original.
    pub variants_per_original: usize,
    /// Specifications to apply (randomly selected).
    pub specifications: Vec<CounterfactualSpec>,
    /// Whether to include the original in output.
    pub include_originals: bool,
}

impl Default for CounterfactualConfig {
    fn default() -> Self {
        Self {
            seed: 42,
            variants_per_original: 3,
            specifications: vec![
                CounterfactualSpec::ScaleAmount { factor: 1.5 },
                CounterfactualSpec::ScaleAmount { factor: 2.0 },
                CounterfactualSpec::ScaleAmount { factor: 0.5 },
                CounterfactualSpec::ShiftDate { days: -7 },
                CounterfactualSpec::ShiftDate { days: 30 },
                CounterfactualSpec::SelfApprove,
            ],
            include_originals: true,
        }
    }
}

// Re-export Decimal for use in specs
use rust_decimal::prelude::*;

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;
    use chrono::NaiveDate;
    use datasynth_core::models::{JournalEntryHeader, JournalEntryLine};

    fn create_test_entry() -> JournalEntry {
        let header = JournalEntryHeader::new(
            "TEST".to_string(),
            NaiveDate::from_ymd_opt(2024, 6, 15).unwrap(),
        );
        let mut entry = JournalEntry::new(header);

        entry.add_line(JournalEntryLine::debit(
            entry.header.document_id,
            1,
            "1100".to_string(),
            Decimal::new(10000, 2), // 100.00
        ));
        entry.add_line(JournalEntryLine::credit(
            entry.header.document_id,
            2,
            "2000".to_string(),
            Decimal::new(10000, 2), // 100.00
        ));

        entry
    }

    #[test]
    fn test_counterfactual_generator_scale_amount() {
        let mut generator = CounterfactualGenerator::new(42);
        let original = create_test_entry();
        let spec = CounterfactualSpec::ScaleAmount { factor: 2.0 };

        let pair = generator.generate(&original, &spec);

        assert_eq!(pair.original.total_debit(), Decimal::new(10000, 2));
        assert_eq!(pair.modified.total_debit(), Decimal::new(20000, 2));
        // ScaleAmount with factor <= 2.0 is statistical anomaly, not fraud
        assert!(!pair.modified.header.is_fraud);
    }

    #[test]
    fn test_counterfactual_generator_shift_date() {
        let mut generator = CounterfactualGenerator::new(42);
        let original = create_test_entry();
        let spec = CounterfactualSpec::ShiftDate { days: -7 };

        let pair = generator.generate(&original, &spec);

        let expected_date = NaiveDate::from_ymd_opt(2024, 6, 8).unwrap();
        assert_eq!(pair.modified.header.posting_date, expected_date);
    }

    #[test]
    fn test_counterfactual_spec_to_anomaly_type() {
        let spec = CounterfactualSpec::SelfApprove;
        let anomaly_type = spec.to_anomaly_type();

        // SelfApprove is classified as Fraud (FraudType::SelfApproval)
        assert!(matches!(
            anomaly_type,
            AnomalyType::Fraud(FraudType::SelfApproval)
        ));
    }

    #[test]
    fn test_counterfactual_batch_generation() {
        let mut generator = CounterfactualGenerator::new(42);
        let original = create_test_entry();
        let specs = vec![
            CounterfactualSpec::ScaleAmount { factor: 1.5 },
            CounterfactualSpec::ShiftDate { days: -3 },
            CounterfactualSpec::SelfApprove,
        ];

        let pairs = generator.generate_batch(&original, &specs);

        assert_eq!(pairs.len(), 3);
        // Only fraud types (ShiftDate, SelfApprove) set is_fraud = true
        // ScaleAmount with factor <= 2.0 is statistical, not fraud
        assert!(!pairs[0].modified.header.is_fraud); // ScaleAmount -> Statistical
        assert!(pairs[1].modified.header.is_fraud); // ShiftDate -> TimingAnomaly (Fraud)
        assert!(pairs[2].modified.header.is_fraud); // SelfApprove -> SelfApproval (Fraud)
    }
}