Skip to main content

datasynth_generators/project_accounting/
revenue_generator.rs

1//! Project revenue recognition generator (Percentage of Completion).
2//!
3//! Takes project cost lines and project contract values to compute revenue
4//! recognition using the cost-to-cost PoC method (ASC 606 input method).
5use chrono::{Datelike, NaiveDate};
6use datasynth_config::schema::ProjectRevenueRecognitionConfig;
7use datasynth_core::models::{
8    CompletionMeasure, Project, ProjectCostLine, ProjectRevenue, RevenueMethod,
9};
10use datasynth_core::utils::seeded_rng;
11use datasynth_core::uuid_factory::{DeterministicUuidFactory, GeneratorType};
12use rand::prelude::*;
13use rand_chacha::ChaCha8Rng;
14use rust_decimal::Decimal;
15use rust_decimal_macros::dec;
16
17/// Generates [`ProjectRevenue`] records using Percentage of Completion.
18///
19/// Not yet wired into the runtime orchestrator; will be integrated alongside
20/// project revenue recognition support.
21#[allow(dead_code)]
22pub struct RevenueGenerator {
23    rng: ChaCha8Rng,
24    uuid_factory: DeterministicUuidFactory,
25    config: ProjectRevenueRecognitionConfig,
26    counter: u64,
27}
28
29impl RevenueGenerator {
30    /// Create a new revenue generator.
31    pub fn new(config: ProjectRevenueRecognitionConfig, seed: u64) -> Self {
32        Self {
33            rng: seeded_rng(seed, 0),
34            uuid_factory: DeterministicUuidFactory::new(seed, GeneratorType::ProjectAccounting),
35            config,
36            counter: 0,
37        }
38    }
39
40    /// Generate revenue recognition records for customer projects.
41    ///
42    /// Only generates revenue for projects that have contract values (customer projects).
43    /// Revenue is computed per month using the cost-to-cost PoC method.
44    pub fn generate(
45        &mut self,
46        projects: &[Project],
47        cost_lines: &[ProjectCostLine],
48        contract_values: &[(String, Decimal, Decimal)], // (project_id, contract_value, estimated_total_cost)
49        start_date: NaiveDate,
50        end_date: NaiveDate,
51    ) -> Vec<ProjectRevenue> {
52        let mut revenues = Vec::new();
53
54        for (project_id, contract_value, estimated_total_cost) in contract_values {
55            let project = match projects.iter().find(|p| &p.project_id == project_id) {
56                Some(p) => p,
57                None => continue,
58            };
59
60            // Collect cost lines for this project, sorted by date
61            let mut project_costs: Vec<&ProjectCostLine> = cost_lines
62                .iter()
63                .filter(|cl| &cl.project_id == project_id)
64                .collect();
65            project_costs.sort_by_key(|cl| cl.posting_date);
66
67            // Generate monthly revenue records
68            let mut current = start_date;
69            let mut prev_cumulative_revenue = dec!(0);
70            let mut billed_to_date = dec!(0);
71
72            while current <= end_date {
73                let period_end = end_of_month(current);
74                let costs_to_date: Decimal = project_costs
75                    .iter()
76                    .filter(|cl| cl.posting_date <= period_end)
77                    .map(|cl| cl.amount)
78                    .sum();
79
80                if costs_to_date.is_zero() {
81                    current = next_month_start(current);
82                    continue;
83                }
84
85                let completion_pct = if estimated_total_cost.is_zero() {
86                    dec!(0)
87                } else {
88                    (costs_to_date / estimated_total_cost)
89                        .min(dec!(1.0))
90                        .round_dp(4)
91                };
92
93                let cumulative_revenue = (*contract_value * completion_pct).round_dp(2);
94                let period_revenue = (cumulative_revenue - prev_cumulative_revenue).max(dec!(0));
95
96                // Billing lags behind recognition by a random factor
97                let billing_pct: f64 = self.rng.random_range(0.70..0.95);
98                let target_billed = cumulative_revenue
99                    * Decimal::from_f64_retain(billing_pct).unwrap_or(dec!(0.85));
100                if target_billed > billed_to_date {
101                    billed_to_date = target_billed.round_dp(2);
102                }
103
104                let unbilled_revenue = (cumulative_revenue - billed_to_date).round_dp(2);
105                let gross_margin_pct = if contract_value.is_zero() {
106                    dec!(0)
107                } else {
108                    ((*contract_value - *estimated_total_cost) / *contract_value).round_dp(4)
109                };
110
111                self.counter += 1;
112                let rev = ProjectRevenue {
113                    id: format!("PREV-{:06}", self.counter),
114                    project_id: project_id.clone(),
115                    entity_id: project.company_code.clone(),
116                    period_start: current,
117                    period_end,
118                    contract_value: *contract_value,
119                    estimated_total_cost: *estimated_total_cost,
120                    costs_to_date,
121                    completion_pct,
122                    method: RevenueMethod::PercentageOfCompletion,
123                    measure: CompletionMeasure::CostToCost,
124                    cumulative_revenue,
125                    period_revenue,
126                    billed_to_date,
127                    unbilled_revenue,
128                    gross_margin_pct,
129                };
130
131                prev_cumulative_revenue = cumulative_revenue;
132                revenues.push(rev);
133                current = next_month_start(current);
134            }
135        }
136
137        revenues
138    }
139}
140
141/// Get the last day of a month.
142#[allow(dead_code)]
143fn end_of_month(date: NaiveDate) -> NaiveDate {
144    let (year, month) = if date.month() == 12 {
145        (date.year() + 1, 1)
146    } else {
147        (date.year(), date.month() + 1)
148    };
149    NaiveDate::from_ymd_opt(year, month, 1)
150        .expect("valid date")
151        .pred_opt()
152        .expect("valid date")
153}
154
155/// Get the first day of the next month.
156#[allow(dead_code)]
157fn next_month_start(date: NaiveDate) -> NaiveDate {
158    let (year, month) = if date.month() == 12 {
159        (date.year() + 1, 1)
160    } else {
161        (date.year(), date.month() + 1)
162    };
163    NaiveDate::from_ymd_opt(year, month, 1).expect("valid date")
164}
165
166#[cfg(test)]
167#[allow(clippy::unwrap_used)]
168mod tests {
169    use super::*;
170    use datasynth_core::models::{CostCategory, CostSourceType, ProjectType};
171
172    fn d(s: &str) -> NaiveDate {
173        NaiveDate::parse_from_str(s, "%Y-%m-%d").unwrap()
174    }
175
176    fn test_project() -> Project {
177        Project::new("PRJ-001", "Customer Build", ProjectType::Customer)
178            .with_budget(dec!(800000))
179            .with_company("TEST")
180    }
181
182    fn test_cost_lines() -> Vec<ProjectCostLine> {
183        // Create cost lines spread across 3 months
184        let months = [
185            (d("2024-01-15"), dec!(100000)),
186            (d("2024-02-15"), dec!(150000)),
187            (d("2024-03-15"), dec!(200000)),
188        ];
189        let mut lines = Vec::new();
190        for (i, (date, amount)) in months.iter().enumerate() {
191            lines.push(ProjectCostLine::new(
192                format!("PCL-{:03}", i + 1),
193                "PRJ-001",
194                "PRJ-001.01",
195                "TEST",
196                *date,
197                CostCategory::Labor,
198                CostSourceType::TimeEntry,
199                format!("TE-{:03}", i + 1),
200                *amount,
201                "USD",
202            ));
203        }
204        lines
205    }
206
207    #[test]
208    fn test_revenue_increases_monotonically() {
209        let project = test_project();
210        let cost_lines = test_cost_lines();
211        let contracts = vec![("PRJ-001".to_string(), dec!(1000000), dec!(800000))];
212
213        let config = ProjectRevenueRecognitionConfig::default();
214        let mut gen = RevenueGenerator::new(config, 42);
215        let revenues = gen.generate(
216            &[project],
217            &cost_lines,
218            &contracts,
219            d("2024-01-01"),
220            d("2024-03-31"),
221        );
222
223        assert!(!revenues.is_empty(), "Should generate revenue records");
224
225        let mut prev_cumulative = dec!(0);
226        for rev in &revenues {
227            assert!(
228                rev.cumulative_revenue >= prev_cumulative,
229                "Revenue should increase monotonically: {} >= {}",
230                rev.cumulative_revenue,
231                prev_cumulative
232            );
233            prev_cumulative = rev.cumulative_revenue;
234        }
235    }
236
237    #[test]
238    fn test_unbilled_revenue_calculation() {
239        let project = test_project();
240        let cost_lines = test_cost_lines();
241        let contracts = vec![("PRJ-001".to_string(), dec!(1000000), dec!(800000))];
242
243        let config = ProjectRevenueRecognitionConfig::default();
244        let mut gen = RevenueGenerator::new(config, 42);
245        let revenues = gen.generate(
246            &[project],
247            &cost_lines,
248            &contracts,
249            d("2024-01-01"),
250            d("2024-03-31"),
251        );
252
253        for rev in &revenues {
254            let expected_unbilled = (rev.cumulative_revenue - rev.billed_to_date).round_dp(2);
255            assert_eq!(
256                rev.unbilled_revenue, expected_unbilled,
257                "Unbilled revenue = recognized - billed"
258            );
259        }
260    }
261
262    #[test]
263    fn test_poc_completion_calculation() {
264        let project = test_project();
265        let cost_lines = test_cost_lines();
266        let contracts = vec![("PRJ-001".to_string(), dec!(1000000), dec!(800000))];
267
268        let config = ProjectRevenueRecognitionConfig::default();
269        let mut gen = RevenueGenerator::new(config, 42);
270        let revenues = gen.generate(
271            &[project],
272            &cost_lines,
273            &contracts,
274            d("2024-01-01"),
275            d("2024-03-31"),
276        );
277
278        // After month 1: costs 100000 / 800000 = 0.125
279        assert_eq!(revenues[0].completion_pct, dec!(0.1250));
280        // After month 2: costs 250000 / 800000 = 0.3125
281        assert_eq!(revenues[1].completion_pct, dec!(0.3125));
282        // After month 3: costs 450000 / 800000 = 0.5625
283        assert_eq!(revenues[2].completion_pct, dec!(0.5625));
284    }
285
286    #[test]
287    fn test_no_revenue_without_costs() {
288        let project = test_project();
289        let contracts = vec![("PRJ-001".to_string(), dec!(1000000), dec!(800000))];
290
291        let config = ProjectRevenueRecognitionConfig::default();
292        let mut gen = RevenueGenerator::new(config, 42);
293        let revenues = gen.generate(
294            &[project],
295            &[], // No cost lines
296            &contracts,
297            d("2024-01-01"),
298            d("2024-03-31"),
299        );
300
301        assert!(revenues.is_empty(), "No costs should produce no revenue");
302    }
303
304    #[test]
305    fn test_deterministic_revenue() {
306        let project = test_project();
307        let cost_lines = test_cost_lines();
308        let contracts = vec![("PRJ-001".to_string(), dec!(1000000), dec!(800000))];
309
310        let config = ProjectRevenueRecognitionConfig::default();
311        let mut gen1 = RevenueGenerator::new(config.clone(), 42);
312        let rev1 = gen1.generate(
313            &[project.clone()],
314            &cost_lines,
315            &contracts,
316            d("2024-01-01"),
317            d("2024-03-31"),
318        );
319
320        let mut gen2 = RevenueGenerator::new(config, 42);
321        let rev2 = gen2.generate(
322            &[project],
323            &cost_lines,
324            &contracts,
325            d("2024-01-01"),
326            d("2024-03-31"),
327        );
328
329        assert_eq!(rev1.len(), rev2.len());
330        for (r1, r2) in rev1.iter().zip(rev2.iter()) {
331            assert_eq!(r1.cumulative_revenue, r2.cumulative_revenue);
332            assert_eq!(r1.billed_to_date, r2.billed_to_date);
333        }
334    }
335}