Skip to main content

datasynth_generators/sourcing/
spend_analysis_generator.rs

1//! Spend analysis generator.
2//!
3//! Analyzes vendor spend to identify sourcing opportunities.
4
5use datasynth_config::schema::SpendAnalysisConfig;
6use datasynth_core::models::sourcing::{SpendAnalysis, VendorSpendShare};
7use rand::prelude::*;
8use rand_chacha::ChaCha8Rng;
9use rust_decimal::Decimal;
10
11/// Generates spend analysis records from vendor pool and transaction data.
12pub struct SpendAnalysisGenerator {
13    rng: ChaCha8Rng,
14    config: SpendAnalysisConfig,
15}
16
17impl SpendAnalysisGenerator {
18    /// Create a new spend analysis generator.
19    pub fn new(seed: u64) -> Self {
20        Self {
21            rng: ChaCha8Rng::seed_from_u64(seed),
22            config: SpendAnalysisConfig::default(),
23        }
24    }
25
26    /// Create with custom configuration.
27    pub fn with_config(seed: u64, config: SpendAnalysisConfig) -> Self {
28        Self {
29            rng: ChaCha8Rng::seed_from_u64(seed),
30            config,
31        }
32    }
33
34    /// Generate spend analysis for a set of vendor-category pairs.
35    ///
36    /// # Arguments
37    /// * `company_code` - Company code
38    /// * `vendor_ids` - Available vendor IDs
39    /// * `categories` - Spend categories (category_id, category_name)
40    /// * `fiscal_year` - Analysis period
41    pub fn generate(
42        &mut self,
43        company_code: &str,
44        vendor_ids: &[String],
45        categories: &[(String, String)],
46        fiscal_year: u16,
47    ) -> Vec<SpendAnalysis> {
48        let mut analyses = Vec::new();
49
50        for (cat_id, cat_name) in categories {
51            // Assign random vendors to this category
52            let vendor_count = self.rng.gen_range(3..=vendor_ids.len().min(15));
53            let mut cat_vendors: Vec<&String> = vendor_ids
54                .choose_multiple(&mut self.rng, vendor_count)
55                .collect();
56            cat_vendors.shuffle(&mut self.rng);
57
58            // Generate spend shares using Pareto-like distribution
59            let mut raw_shares: Vec<f64> = (0..cat_vendors.len())
60                .map(|i| 1.0 / ((i as f64 + 1.0).powf(0.8)))
61                .collect();
62            let total: f64 = raw_shares.iter().sum();
63            for s in &mut raw_shares {
64                *s /= total;
65            }
66
67            let total_spend = Decimal::from(self.rng.gen_range(100_000i64..=5_000_000));
68            let transaction_count = self.rng.gen_range(50..=2000);
69
70            // Calculate HHI
71            let hhi: f64 = raw_shares.iter().map(|s| (s * 100.0).powi(2)).sum();
72
73            let contract_coverage = self.rng.gen_range(0.3..=0.95);
74            let preferred_coverage = contract_coverage * self.rng.gen_range(0.7..=1.0);
75
76            let vendor_shares: Vec<VendorSpendShare> = cat_vendors
77                .iter()
78                .zip(raw_shares.iter())
79                .map(|(vid, share)| VendorSpendShare {
80                    vendor_id: vid.to_string(),
81                    vendor_name: format!("Vendor {}", vid),
82                    spend_amount: Decimal::from_f64_retain(
83                        total_spend.to_string().parse::<f64>().unwrap_or(0.0) * share,
84                    )
85                    .unwrap_or(Decimal::ZERO),
86                    share: *share,
87                    is_preferred: *share > 0.15 && self.rng.gen_bool(preferred_coverage),
88                })
89                .collect();
90
91            analyses.push(SpendAnalysis {
92                category_id: cat_id.clone(),
93                category_name: cat_name.clone(),
94                company_code: company_code.to_string(),
95                total_spend,
96                vendor_count: cat_vendors.len() as u32,
97                transaction_count,
98                hhi_index: hhi,
99                vendor_shares,
100                contract_coverage,
101                preferred_vendor_coverage: preferred_coverage,
102                price_trend_pct: self.rng.gen_range(-0.05..=0.10),
103                fiscal_year,
104            });
105        }
106
107        analyses
108    }
109
110    /// Get the HHI threshold from config.
111    pub fn hhi_threshold(&self) -> f64 {
112        self.config.hhi_threshold
113    }
114}
115
116#[cfg(test)]
117#[allow(clippy::unwrap_used)]
118mod tests {
119    use super::*;
120
121    fn test_vendor_ids() -> Vec<String> {
122        (1..=10).map(|i| format!("V{:04}", i)).collect()
123    }
124
125    fn test_categories() -> Vec<(String, String)> {
126        vec![
127            ("CAT-001".to_string(), "Office Supplies".to_string()),
128            ("CAT-002".to_string(), "IT Equipment".to_string()),
129        ]
130    }
131
132    #[test]
133    fn test_basic_generation() {
134        let mut gen = SpendAnalysisGenerator::new(42);
135        let results = gen.generate("C001", &test_vendor_ids(), &test_categories(), 2024);
136
137        assert_eq!(results.len(), 2);
138        for analysis in &results {
139            assert_eq!(analysis.company_code, "C001");
140            assert_eq!(analysis.fiscal_year, 2024);
141            assert!(!analysis.category_id.is_empty());
142            assert!(!analysis.category_name.is_empty());
143            assert!(analysis.vendor_count > 0);
144            assert!(analysis.transaction_count > 0);
145            assert!(analysis.total_spend > Decimal::ZERO);
146            assert!(analysis.hhi_index > 0.0);
147            assert!(!analysis.vendor_shares.is_empty());
148        }
149    }
150
151    #[test]
152    fn test_deterministic() {
153        let mut gen1 = SpendAnalysisGenerator::new(42);
154        let mut gen2 = SpendAnalysisGenerator::new(42);
155        let vendors = test_vendor_ids();
156        let cats = test_categories();
157
158        let r1 = gen1.generate("C001", &vendors, &cats, 2024);
159        let r2 = gen2.generate("C001", &vendors, &cats, 2024);
160
161        assert_eq!(r1.len(), r2.len());
162        for (a, b) in r1.iter().zip(r2.iter()) {
163            assert_eq!(a.category_id, b.category_id);
164            assert_eq!(a.total_spend, b.total_spend);
165            assert_eq!(a.vendor_count, b.vendor_count);
166            assert_eq!(a.transaction_count, b.transaction_count);
167        }
168    }
169
170    #[test]
171    fn test_field_constraints() {
172        let mut gen = SpendAnalysisGenerator::new(99);
173        let results = gen.generate("C001", &test_vendor_ids(), &test_categories(), 2024);
174
175        for analysis in &results {
176            // Shares should sum to approximately 1.0
177            let share_sum: f64 = analysis.vendor_shares.iter().map(|s| s.share).sum();
178            assert!(
179                (share_sum - 1.0).abs() < 0.01,
180                "shares should sum to ~1.0, got {}",
181                share_sum
182            );
183
184            // Contract coverage and price trend should be in valid range
185            assert!(analysis.contract_coverage >= 0.0 && analysis.contract_coverage <= 1.0);
186            assert!(
187                analysis.preferred_vendor_coverage >= 0.0
188                    && analysis.preferred_vendor_coverage <= 1.0
189            );
190            assert!(analysis.price_trend_pct >= -0.05 && analysis.price_trend_pct <= 0.10);
191
192            // Each vendor share should have a non-empty vendor_id
193            for vs in &analysis.vendor_shares {
194                assert!(!vs.vendor_id.is_empty());
195            }
196        }
197    }
198
199    #[test]
200    fn test_hhi_threshold() {
201        let gen = SpendAnalysisGenerator::new(42);
202        assert_eq!(gen.hhi_threshold(), 2500.0);
203    }
204}