datasynth-generators 5.34.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
//! Integration tests for ISA 530 sampling plans and ISA 315 SCOTS generators.
//!
//! Tests validate:
//! - Key items all have amount ≥ tolerable error
//! - Sample size correlates correctly with CRA level
//! - Sampling interval = remaining_population / sample_size
//! - All standard SCOTs present for a standard entity
//! - Estimation SCOTs have complexity; non-estimation do not
//! - Volume derives from JE data when available

#![allow(clippy::unwrap_used)]

use datasynth_core::models::audit::risk_assessment_cra::{
    AuditAssertion, CombinedRiskAssessment, CraLevel, RiskRating,
};
use datasynth_core::models::audit::sampling_plan::{
    KeyItemReason, SamplingMethodology, SelectionType,
};
use datasynth_core::models::audit::scots::{
    EstimationComplexity, ScotSignificance, ScotTransactionType,
};
use datasynth_generators::audit::sampling_plan_generator::SamplingPlanGenerator;
use datasynth_generators::audit::scots_generator::{ScotsGenerator, ScotsGeneratorConfig};
use rust_decimal::Decimal;
use rust_decimal_macros::dec;

// ============================================================================
// Helpers
// ============================================================================

fn make_cra(
    area: &str,
    assertion: AuditAssertion,
    ir: RiskRating,
    cr: RiskRating,
    significant: bool,
) -> CombinedRiskAssessment {
    CombinedRiskAssessment::new("C001", area, assertion, ir, cr, significant, vec![])
}

fn make_high_cra(area: &str, assertion: AuditAssertion) -> CombinedRiskAssessment {
    make_cra(area, assertion, RiskRating::High, RiskRating::High, true)
}

fn make_moderate_cra(area: &str, assertion: AuditAssertion) -> CombinedRiskAssessment {
    make_cra(
        area,
        assertion,
        RiskRating::Medium,
        RiskRating::Medium,
        false,
    )
}

fn make_low_cra(area: &str, assertion: AuditAssertion) -> CombinedRiskAssessment {
    make_cra(area, assertion, RiskRating::Low, RiskRating::Low, false)
}

const TEST_TE: Decimal = dec!(32_500);

// ============================================================================
// Sampling Plan Tests
// ============================================================================

#[test]
fn sampling_plan_minimal_cra_skipped() {
    let minimal_cra = make_low_cra("Cash", AuditAssertion::Existence);
    assert_eq!(minimal_cra.combined_risk, CraLevel::Minimal);

    let mut gen = SamplingPlanGenerator::new(42);
    let (plans, items) = gen.generate_for_cras(&[minimal_cra], Some(TEST_TE));

    assert!(
        plans.is_empty(),
        "Minimal CRA should produce no sampling plan"
    );
    assert!(
        items.is_empty(),
        "Minimal CRA should produce no sampled items"
    );
}

#[test]
fn sampling_plan_low_cra_skipped() {
    // Low + Medium = Low CRA
    let low_cra = make_cra(
        "Cost of Sales",
        AuditAssertion::Occurrence,
        RiskRating::Low,
        RiskRating::Medium,
        false,
    );
    assert_eq!(low_cra.combined_risk, CraLevel::Low);

    let mut gen = SamplingPlanGenerator::new(42);
    let (plans, _) = gen.generate_for_cras(&[low_cra], Some(TEST_TE));
    assert!(plans.is_empty(), "Low CRA should produce no sampling plan");
}

#[test]
fn sampling_plan_moderate_cra_produces_plan() {
    let cra = make_moderate_cra("Trade Receivables", AuditAssertion::Existence);
    assert_eq!(cra.combined_risk, CraLevel::Moderate);

    let mut gen = SamplingPlanGenerator::new(42);
    let (plans, items) = gen.generate_for_cras(&[cra], Some(TEST_TE));

    assert_eq!(
        plans.len(),
        1,
        "Moderate CRA should produce exactly one plan"
    );
    let plan = &plans[0];
    assert!(
        plan.sample_size >= 20 && plan.sample_size <= 30,
        "Moderate CRA sample size should be 20–30, got {}",
        plan.sample_size
    );
    assert!(!items.is_empty(), "Should produce sampled items");
}

#[test]
fn sampling_plan_high_cra_large_sample() {
    let cra = make_high_cra("Revenue", AuditAssertion::Occurrence);
    assert_eq!(cra.combined_risk, CraLevel::High);

    let mut gen = SamplingPlanGenerator::new(42);
    let (plans, _) = gen.generate_for_cras(&[cra], Some(TEST_TE));

    assert_eq!(plans.len(), 1);
    let plan = &plans[0];
    assert!(
        plan.sample_size >= 40 && plan.sample_size <= 60,
        "High CRA sample size should be 40–60, got {}",
        plan.sample_size
    );
}

#[test]
fn sampling_plan_key_items_all_above_tolerable_error() {
    let cras = vec![
        make_high_cra("Revenue", AuditAssertion::Occurrence),
        make_moderate_cra("Inventory", AuditAssertion::Existence),
        make_high_cra("Provisions", AuditAssertion::ValuationAndAllocation),
    ];

    let mut gen = SamplingPlanGenerator::new(99);
    let (plans, _) = gen.generate_for_cras(&cras, Some(TEST_TE));

    assert!(!plans.is_empty());
    for plan in &plans {
        for ki in &plan.key_items {
            assert!(
                ki.amount >= TEST_TE,
                "Key item {} amount {} must be >= TE {}",
                ki.item_id,
                ki.amount,
                TEST_TE
            );
        }
    }
}

#[test]
fn sampling_plan_first_key_item_always_above_te() {
    let cra = make_high_cra("Trade Receivables", AuditAssertion::ValuationAndAllocation);

    for seed in [1u64, 7, 42, 99, 123] {
        let mut gen = SamplingPlanGenerator::new(seed);
        let (plans, _) = gen.generate_for_cras(std::slice::from_ref(&cra), Some(TEST_TE));
        assert!(!plans.is_empty());
        let ki0 = &plans[0].key_items[0];
        assert_eq!(
            ki0.reason,
            KeyItemReason::AboveTolerableError,
            "First key item must be AboveTolerableError"
        );
        assert!(
            ki0.amount >= TEST_TE,
            "First key item amount {} >= TE {}",
            ki0.amount,
            TEST_TE
        );
    }
}

#[test]
fn sampling_plan_interval_equals_remaining_over_sample_size() {
    let cras = vec![
        make_high_cra("Revenue", AuditAssertion::Occurrence),
        make_moderate_cra("Inventory", AuditAssertion::Existence),
    ];

    let mut gen = SamplingPlanGenerator::new(7);
    let (plans, _) = gen.generate_for_cras(&cras, Some(TEST_TE));

    for plan in &plans {
        if plan.sample_size > 0 && plan.remaining_population_value > Decimal::ZERO {
            let expected = plan.remaining_population_value / Decimal::from(plan.sample_size as i64);
            let diff = (plan.sampling_interval - expected).abs();
            assert!(
                diff < dec!(0.01),
                "Plan '{}': interval {} ≠ remaining/n {}",
                plan.id,
                plan.sampling_interval,
                expected
            );
        }
    }
}

#[test]
fn sampling_plan_key_items_value_sums_correctly() {
    let cra = make_high_cra("Revenue", AuditAssertion::Occurrence);

    let mut gen = SamplingPlanGenerator::new(42);
    let (plans, _) = gen.generate_for_cras(&[cra], Some(TEST_TE));

    assert_eq!(plans.len(), 1);
    let plan = &plans[0];
    let computed_key_value: Decimal = plan.key_items.iter().map(|k| k.amount).sum();
    let diff = (computed_key_value - plan.key_items_value).abs();
    assert!(
        diff < dec!(0.01),
        "key_items_value mismatch: computed={} stored={}",
        computed_key_value,
        plan.key_items_value
    );
}

#[test]
fn sampling_plan_remaining_value_is_population_minus_key_items() {
    let cra = make_moderate_cra("Inventory", AuditAssertion::Existence);

    let mut gen = SamplingPlanGenerator::new(55);
    let (plans, _) = gen.generate_for_cras(&[cra], Some(TEST_TE));

    assert_eq!(plans.len(), 1);
    let plan = &plans[0];
    let expected_remaining = plan.population_value - plan.key_items_value;
    let diff = (plan.remaining_population_value - expected_remaining).abs();
    assert!(diff < dec!(0.01), "remaining_population_value mismatch");
}

#[test]
fn sampling_plan_balance_assertion_uses_mus() {
    let cra = make_moderate_cra("Trade Receivables", AuditAssertion::Existence);

    let mut gen = SamplingPlanGenerator::new(42);
    let (plans, _) = gen.generate_for_cras(&[cra], Some(TEST_TE));

    assert_eq!(plans.len(), 1);
    assert_eq!(
        plans[0].methodology,
        SamplingMethodology::MonetaryUnitSampling,
        "Balance assertion should use MUS"
    );
}

#[test]
fn sampling_plan_transaction_assertion_uses_systematic() {
    let cra = make_moderate_cra("Revenue", AuditAssertion::Occurrence);

    let mut gen = SamplingPlanGenerator::new(42);
    let (plans, _) = gen.generate_for_cras(&[cra], Some(TEST_TE));

    assert_eq!(plans.len(), 1);
    assert_eq!(
        plans[0].methodology,
        SamplingMethodology::SystematicSelection,
        "Transaction assertion should use Systematic"
    );
}

#[test]
fn sampled_items_are_all_tested() {
    let cras = vec![
        make_high_cra("Revenue", AuditAssertion::Occurrence),
        make_moderate_cra("Provisions", AuditAssertion::ValuationAndAllocation),
    ];

    let mut gen = SamplingPlanGenerator::new(33);
    let (_, items) = gen.generate_for_cras(&cras, Some(TEST_TE));

    assert!(!items.is_empty());
    assert!(
        items.iter().all(|i| i.tested),
        "All sampled items should be marked as tested"
    );
}

#[test]
fn sampled_items_include_key_and_representative() {
    let cra = make_high_cra("Provisions", AuditAssertion::ValuationAndAllocation);

    let mut gen = SamplingPlanGenerator::new(42);
    let (_, items) = gen.generate_for_cras(&[cra], Some(TEST_TE));

    let key_count = items
        .iter()
        .filter(|i| i.selection_type == SelectionType::KeyItem)
        .count();
    let rep_count = items
        .iter()
        .filter(|i| i.selection_type == SelectionType::Representative)
        .count();

    assert!(key_count > 0, "Should have key items");
    assert!(rep_count > 0, "Should have representative items");
}

#[test]
fn misstatements_have_nonzero_amount() {
    let cra = make_high_cra("Revenue", AuditAssertion::Occurrence);

    let mut gen = SamplingPlanGenerator::new(42);
    let (_, items) = gen.generate_for_cras(&[cra], Some(TEST_TE));

    for item in items.iter().filter(|i| i.misstatement_found) {
        let amt = item.misstatement_amount.unwrap_or(Decimal::ZERO);
        assert!(
            amt > Decimal::ZERO,
            "Misstatement amount must be > 0 when misstatement_found=true"
        );
    }
}

#[test]
fn sampling_plan_ids_are_unique_across_entities() {
    let cras_c001 = vec![
        make_moderate_cra("Revenue", AuditAssertion::Occurrence),
        make_high_cra("Inventory", AuditAssertion::Existence),
    ];
    let cras_c002 = vec![CombinedRiskAssessment::new(
        "C002",
        "Revenue",
        AuditAssertion::Occurrence,
        RiskRating::Medium,
        RiskRating::Medium,
        false,
        vec![],
    )];

    let mut gen = SamplingPlanGenerator::new(42);
    let te = Some(TEST_TE);
    let (mut plans, _) = gen.generate_for_cras(&cras_c001, te);
    let (plans2, _) = gen.generate_for_cras(&cras_c002, te);
    plans.extend(plans2);

    let ids: std::collections::HashSet<&str> = plans.iter().map(|p| p.id.as_str()).collect();
    assert_eq!(
        ids.len(),
        plans.len(),
        "Plan IDs should be unique across entities"
    );
}

// ============================================================================
// SCOTS Tests
// ============================================================================

#[test]
fn scots_generates_8_standard_scots_without_ic() {
    let mut gen = ScotsGenerator::new(42);
    let scots = gen.generate_for_entity("C001", &[]);

    assert_eq!(
        scots.len(),
        8,
        "Should generate 8 non-IC SCOTs, got {}",
        scots.len()
    );
}

#[test]
fn scots_generates_9_scots_with_ic() {
    let config = ScotsGeneratorConfig {
        intercompany_enabled: true,
        ..ScotsGeneratorConfig::default()
    };
    let mut gen = ScotsGenerator::with_config(42, config);
    let scots = gen.generate_for_entity("C001", &[]);

    assert_eq!(scots.len(), 9, "Should generate 9 SCOTs with IC enabled");
    assert!(
        scots.iter().any(|s| s.business_process == "IC"),
        "IC SCOT should be present"
    );
}

#[test]
fn scots_estimation_types_have_complexity() {
    let mut gen = ScotsGenerator::new(42);
    let scots = gen.generate_for_entity("C001", &[]);

    for s in scots
        .iter()
        .filter(|s| s.transaction_type == ScotTransactionType::Estimation)
    {
        assert!(
            s.estimation_complexity.is_some(),
            "Estimation SCOT '{}' must have estimation_complexity set",
            s.scot_name
        );
    }
}

#[test]
fn scots_non_estimation_types_have_no_complexity() {
    let mut gen = ScotsGenerator::new(42);
    let scots = gen.generate_for_entity("C001", &[]);

    for s in scots
        .iter()
        .filter(|s| s.transaction_type != ScotTransactionType::Estimation)
    {
        assert!(
            s.estimation_complexity.is_none(),
            "Non-estimation SCOT '{}' must not have estimation_complexity",
            s.scot_name
        );
    }
}

#[test]
fn scots_all_have_four_critical_path_stages() {
    let mut gen = ScotsGenerator::new(42);
    let scots = gen.generate_for_entity("C001", &[]);

    for s in &scots {
        assert_eq!(
            s.critical_path.len(),
            4,
            "SCOT '{}' should have 4 critical path stages, got {}",
            s.scot_name,
            s.critical_path.len()
        );
    }
}

#[test]
fn scots_ids_are_unique() {
    let mut gen = ScotsGenerator::new(42);
    let scots = gen.generate_for_entity("C001", &[]);

    let ids: std::collections::HashSet<&str> = scots.iter().map(|s| s.id.as_str()).collect();
    assert_eq!(ids.len(), scots.len(), "SCOT IDs should be unique");
}

#[test]
fn scots_all_have_positive_volume_and_value() {
    let mut gen = ScotsGenerator::new(42);
    let scots = gen.generate_for_entity("C001", &[]);

    for s in &scots {
        assert!(s.volume > 0, "SCOT '{}' volume must be > 0", s.scot_name);
        assert!(
            s.monetary_value > Decimal::ZERO,
            "SCOT '{}' monetary_value must be > 0",
            s.scot_name
        );
    }
}

#[test]
fn scots_expected_scot_names_present() {
    let mut gen = ScotsGenerator::new(42);
    let scots = gen.generate_for_entity("C001", &[]);

    let names: Vec<&str> = scots.iter().map(|s| s.scot_name.as_str()).collect();

    let expected_names = [
        "Revenue — Product Sales",
        "Purchases — Procurement",
        "Payroll",
        "Fixed Asset Additions",
        "Depreciation",
        "Tax Provision",
        "ECL / Bad Debt Provision",
        "Period-End Adjustments",
    ];

    for expected in &expected_names {
        assert!(
            names.contains(expected),
            "Expected SCOT '{}' not found. Present: {:?}",
            expected,
            names
        );
    }
}

#[test]
fn scots_tax_provision_is_complex_estimation() {
    let mut gen = ScotsGenerator::new(42);
    let scots = gen.generate_for_entity("C001", &[]);

    let tax = scots
        .iter()
        .find(|s| s.scot_name == "Tax Provision")
        .expect("Tax Provision SCOT should exist");

    assert_eq!(tax.significance_level, ScotSignificance::High);
    assert_eq!(tax.transaction_type, ScotTransactionType::Estimation);
    assert_eq!(
        tax.estimation_complexity,
        Some(EstimationComplexity::Complex)
    );
    assert_eq!(tax.business_process, "R2R");
}

#[test]
fn scots_depreciation_is_simple_estimation() {
    let mut gen = ScotsGenerator::new(42);
    let scots = gen.generate_for_entity("C001", &[]);

    let dep = scots
        .iter()
        .find(|s| s.scot_name == "Depreciation")
        .expect("Depreciation SCOT should exist");

    assert_eq!(dep.transaction_type, ScotTransactionType::Estimation);
    assert_eq!(
        dep.estimation_complexity,
        Some(EstimationComplexity::Simple)
    );
}

#[test]
fn scots_ecl_is_moderate_estimation() {
    let mut gen = ScotsGenerator::new(42);
    let scots = gen.generate_for_entity("C001", &[]);

    let ecl = scots
        .iter()
        .find(|s| s.scot_name == "ECL / Bad Debt Provision")
        .expect("ECL SCOT should exist");

    assert_eq!(ecl.transaction_type, ScotTransactionType::Estimation);
    assert_eq!(
        ecl.estimation_complexity,
        Some(EstimationComplexity::Moderate)
    );
    assert_eq!(ecl.significance_level, ScotSignificance::High);
}

#[test]
fn scots_revenue_is_o2c_high_routine() {
    let mut gen = ScotsGenerator::new(42);
    let scots = gen.generate_for_entity("C001", &[]);

    let rev = scots
        .iter()
        .find(|s| s.scot_name == "Revenue — Product Sales")
        .expect("Revenue SCOT should exist");

    assert_eq!(rev.business_process, "O2C");
    assert_eq!(rev.significance_level, ScotSignificance::High);
    assert_eq!(rev.transaction_type, ScotTransactionType::Routine);
}

#[test]
fn scots_multiple_entities_get_separate_sets() {
    let mut gen = ScotsGenerator::new(42);
    let scots_c001 = gen.generate_for_entity("C001", &[]);
    let scots_c002 = gen.generate_for_entity("C002", &[]);

    assert_eq!(
        scots_c001.len(),
        scots_c002.len(),
        "Both entities should get same number of SCOTs"
    );

    // IDs should differ between entities
    let ids_c001: std::collections::HashSet<&str> =
        scots_c001.iter().map(|s| s.id.as_str()).collect();
    let ids_c002: std::collections::HashSet<&str> =
        scots_c002.iter().map(|s| s.id.as_str()).collect();
    let overlap: Vec<_> = ids_c001.intersection(&ids_c002).collect();
    assert!(
        overlap.is_empty(),
        "SCOT IDs should be unique across entities: {:?}",
        overlap
    );
}

#[test]
fn scots_relevant_assertions_are_non_empty() {
    let mut gen = ScotsGenerator::new(42);
    let scots = gen.generate_for_entity("C001", &[]);

    for s in &scots {
        assert!(
            !s.relevant_assertions.is_empty(),
            "SCOT '{}' must have at least one relevant assertion",
            s.scot_name
        );
    }
}

#[test]
fn scots_related_account_areas_are_non_empty() {
    let mut gen = ScotsGenerator::new(42);
    let scots = gen.generate_for_entity("C001", &[]);

    for s in &scots {
        assert!(
            !s.related_account_areas.is_empty(),
            "SCOT '{}' must have at least one related account area",
            s.scot_name
        );
    }
}

// ============================================================================
// key_item_reason propagation (v4.2.3)
// ============================================================================
//
// `SampledItem.key_item_reason` was added so SDK consumers can see why a key
// item was selected without cross-referencing `SamplingPlan.key_items[]`.
// Representative-sample rows keep it None.

#[test]
fn sampled_items_key_item_reason_populated_for_key_items_only() {
    let cra = make_high_cra("Revenue", AuditAssertion::Occurrence);
    let mut gen = SamplingPlanGenerator::new(42);
    let (plans, items) = gen.generate_for_cras(std::slice::from_ref(&cra), Some(TEST_TE));
    assert!(!plans.is_empty());
    assert!(!items.is_empty());

    let plan = &plans[0];
    let plan_items: Vec<_> = items
        .iter()
        .filter(|i| i.sampling_plan_id == plan.id)
        .collect();

    let mut key_item_rows = 0;
    let mut rep_rows = 0;
    for item in &plan_items {
        match item.selection_type {
            SelectionType::KeyItem => {
                key_item_rows += 1;
                let reason = item.key_item_reason.expect(
                    "key-item row must carry key_item_reason — consumers depend on \
                     this field to avoid re-joining against SamplingPlan.key_items[]",
                );
                // Reason must match the parent plan's key_items[] entry by item_id.
                let parent_ki = plan
                    .key_items
                    .iter()
                    .find(|ki| ki.item_id == item.item_id)
                    .expect("key-item row must reference a KeyItem in the plan");
                assert_eq!(
                    reason, parent_ki.reason,
                    "key_item_reason must match the source KeyItem.reason for {}",
                    item.item_id
                );
            }
            SelectionType::Representative => {
                rep_rows += 1;
                assert!(
                    item.key_item_reason.is_none(),
                    "representative-sample row must not carry key_item_reason \
                     (item_id={})",
                    item.item_id
                );
            }
        }
    }
    assert!(
        key_item_rows > 0,
        "test plan should contain at least one key-item row"
    );
    assert!(
        rep_rows > 0,
        "test plan should contain at least one representative row"
    );
}