datasynth-standards 4.2.1

Accounting and audit standards framework for synthetic data generation (IFRS, US GAAP, ISA, SOX, PCAOB)
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
//! Revenue Recognition Models (ASC 606 / IFRS 15).
//!
//! Implements the five-step model for revenue recognition:
//! 1. Identify the contract with a customer
//! 2. Identify the performance obligations
//! 3. Determine the transaction price
//! 4. Allocate the transaction price
//! 5. Recognize revenue when performance obligations are satisfied
//!
//! This module generates realistic customer contracts, performance obligations,
//! and revenue recognition schedules that comply with ASC 606 / IFRS 15.

use chrono::NaiveDate;
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::framework::AccountingFramework;

/// Customer contract for revenue recognition.
///
/// Represents Step 1 of the revenue recognition model: identifying
/// the contract with the customer.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CustomerContract {
    /// Unique contract identifier.
    pub contract_id: Uuid,

    /// Reference to the customer entity.
    pub customer_id: String,

    /// Customer name for reporting.
    pub customer_name: String,

    /// Company code this contract belongs to.
    pub company_code: String,

    /// Contract inception date.
    pub inception_date: NaiveDate,

    /// Contract end date (if determinable).
    pub end_date: Option<NaiveDate>,

    /// Total transaction price before allocation.
    #[serde(with = "datasynth_core::serde_decimal")]
    pub transaction_price: Decimal,

    /// Currency of the contract.
    pub currency: String,

    /// Contract status.
    pub status: ContractStatus,

    /// Performance obligations within this contract.
    pub performance_obligations: Vec<PerformanceObligation>,

    /// Variable consideration components.
    pub variable_consideration: Vec<VariableConsideration>,

    /// Whether contract contains a significant financing component.
    pub has_significant_financing: bool,

    /// Discount rate for significant financing component.
    #[serde(default, with = "datasynth_core::serde_decimal::option")]
    pub financing_rate: Option<Decimal>,

    /// Accounting framework applied.
    pub framework: AccountingFramework,

    /// Contract modification history.
    pub modifications: Vec<ContractModification>,

    /// Reference to related sales order (O2C integration).
    pub sales_order_id: Option<Uuid>,

    /// Reference to related journal entries.
    #[serde(default)]
    pub journal_entry_ids: Vec<Uuid>,
}

impl CustomerContract {
    /// Create a new customer contract.
    pub fn new(
        customer_id: impl Into<String>,
        customer_name: impl Into<String>,
        company_code: impl Into<String>,
        inception_date: NaiveDate,
        transaction_price: Decimal,
        currency: impl Into<String>,
        framework: AccountingFramework,
    ) -> Self {
        Self {
            contract_id: Uuid::now_v7(),
            customer_id: customer_id.into(),
            customer_name: customer_name.into(),
            company_code: company_code.into(),
            inception_date,
            end_date: None,
            transaction_price,
            currency: currency.into(),
            status: ContractStatus::Active,
            performance_obligations: Vec::new(),
            variable_consideration: Vec::new(),
            has_significant_financing: false,
            financing_rate: None,
            framework,
            modifications: Vec::new(),
            sales_order_id: None,
            journal_entry_ids: Vec::new(),
        }
    }

    /// Add a performance obligation to the contract.
    pub fn add_performance_obligation(&mut self, obligation: PerformanceObligation) {
        self.performance_obligations.push(obligation);
    }

    /// Add variable consideration component.
    pub fn add_variable_consideration(&mut self, vc: VariableConsideration) {
        self.variable_consideration.push(vc);
    }

    /// Calculate total allocated transaction price across all obligations.
    pub fn total_allocated_price(&self) -> Decimal {
        self.performance_obligations
            .iter()
            .map(|po| po.allocated_price)
            .sum()
    }

    /// Calculate total revenue recognized to date.
    pub fn total_revenue_recognized(&self) -> Decimal {
        self.performance_obligations
            .iter()
            .map(|po| po.revenue_recognized)
            .sum()
    }

    /// Calculate total deferred revenue (contract liability).
    pub fn total_deferred_revenue(&self) -> Decimal {
        self.performance_obligations
            .iter()
            .map(|po| po.deferred_revenue)
            .sum()
    }

    /// Check if contract is fully satisfied.
    pub fn is_fully_satisfied(&self) -> bool {
        self.performance_obligations
            .iter()
            .all(PerformanceObligation::is_satisfied)
    }
}

/// Contract status for lifecycle tracking.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum ContractStatus {
    /// Contract is pending approval or execution.
    Pending,
    /// Contract is active and obligations are being performed.
    #[default]
    Active,
    /// Contract has been modified (superseded by new contract).
    Modified,
    /// Contract is complete - all obligations satisfied.
    Complete,
    /// Contract has been terminated.
    Terminated,
    /// Contract is in dispute.
    Disputed,
}

impl std::fmt::Display for ContractStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Pending => write!(f, "Pending"),
            Self::Active => write!(f, "Active"),
            Self::Modified => write!(f, "Modified"),
            Self::Complete => write!(f, "Complete"),
            Self::Terminated => write!(f, "Terminated"),
            Self::Disputed => write!(f, "Disputed"),
        }
    }
}

/// Performance obligation within a customer contract.
///
/// Represents Step 2 of the revenue recognition model: identifying
/// distinct goods or services promised in the contract.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceObligation {
    /// Unique obligation identifier.
    pub obligation_id: Uuid,

    /// Parent contract ID.
    pub contract_id: Uuid,

    /// Sequence number within contract.
    pub sequence: u32,

    /// Description of the promised good or service.
    pub description: String,

    /// Type of obligation.
    pub obligation_type: ObligationType,

    /// Pattern of satisfaction.
    pub satisfaction_pattern: SatisfactionPattern,

    /// Method for measuring progress (for over-time recognition).
    pub progress_method: Option<ProgressMethod>,

    /// Standalone selling price for allocation.
    #[serde(with = "datasynth_core::serde_decimal")]
    pub standalone_selling_price: Decimal,

    /// Allocated transaction price (Step 4).
    #[serde(with = "datasynth_core::serde_decimal")]
    pub allocated_price: Decimal,

    /// Percentage complete (0-100).
    #[serde(with = "datasynth_core::serde_decimal")]
    pub progress_percent: Decimal,

    /// Revenue recognized to date.
    #[serde(with = "datasynth_core::serde_decimal")]
    pub revenue_recognized: Decimal,

    /// Deferred revenue (contract liability).
    #[serde(with = "datasynth_core::serde_decimal")]
    pub deferred_revenue: Decimal,

    /// Unbilled receivable (contract asset).
    #[serde(with = "datasynth_core::serde_decimal")]
    pub contract_asset: Decimal,

    /// Date obligation was satisfied (if complete).
    pub satisfaction_date: Option<NaiveDate>,

    /// Expected satisfaction date.
    pub expected_satisfaction_date: Option<NaiveDate>,

    /// Material right granted to customer.
    pub material_right: Option<MaterialRight>,
}

impl PerformanceObligation {
    /// Create a new performance obligation.
    pub fn new(
        contract_id: Uuid,
        sequence: u32,
        description: impl Into<String>,
        obligation_type: ObligationType,
        satisfaction_pattern: SatisfactionPattern,
        standalone_selling_price: Decimal,
    ) -> Self {
        Self {
            obligation_id: Uuid::now_v7(),
            contract_id,
            sequence,
            description: description.into(),
            obligation_type,
            satisfaction_pattern,
            progress_method: match satisfaction_pattern {
                SatisfactionPattern::OverTime => Some(ProgressMethod::default()),
                SatisfactionPattern::PointInTime => None,
            },
            standalone_selling_price,
            allocated_price: Decimal::ZERO,
            progress_percent: Decimal::ZERO,
            revenue_recognized: Decimal::ZERO,
            deferred_revenue: Decimal::ZERO,
            contract_asset: Decimal::ZERO,
            satisfaction_date: None,
            expected_satisfaction_date: None,
            material_right: None,
        }
    }

    /// Check if obligation is fully satisfied.
    pub fn is_satisfied(&self) -> bool {
        self.satisfaction_date.is_some() || self.progress_percent >= Decimal::from(100)
    }

    /// Update progress and calculate revenue to recognize.
    pub fn update_progress(&mut self, new_progress: Decimal, as_of_date: NaiveDate) {
        let old_revenue = self.revenue_recognized;
        self.progress_percent = new_progress.min(Decimal::from(100));

        // Calculate revenue based on progress
        let target_revenue = self.allocated_price * self.progress_percent / Decimal::from(100);
        self.revenue_recognized = target_revenue;
        self.deferred_revenue = self.allocated_price - self.revenue_recognized;

        // Mark as satisfied if 100% complete
        if self.progress_percent >= Decimal::from(100) && self.satisfaction_date.is_none() {
            self.satisfaction_date = Some(as_of_date);
        }

        // Contract asset exists when revenue recognized exceeds billing
        // This would need billing information to calculate accurately
        let _ = old_revenue; // Used for incremental calculations
    }
}

/// Type of performance obligation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum ObligationType {
    /// Physical product delivery.
    #[default]
    Good,
    /// Service performance.
    Service,
    /// License grant (functional or symbolic).
    License,
    /// Series of distinct goods/services that are substantially the same.
    Series,
    /// Warranty beyond assurance-type.
    ServiceTypeWarranty,
    /// Option that provides material right.
    MaterialRight,
}

impl std::fmt::Display for ObligationType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Good => write!(f, "Good"),
            Self::Service => write!(f, "Service"),
            Self::License => write!(f, "License"),
            Self::Series => write!(f, "Series"),
            Self::ServiceTypeWarranty => write!(f, "Service-Type Warranty"),
            Self::MaterialRight => write!(f, "Material Right"),
        }
    }
}

/// Pattern for satisfying performance obligations.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum SatisfactionPattern {
    /// Revenue recognized at a point in time (e.g., delivery).
    #[default]
    PointInTime,
    /// Revenue recognized over time as performance occurs.
    OverTime,
}

impl std::fmt::Display for SatisfactionPattern {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::PointInTime => write!(f, "Point in Time"),
            Self::OverTime => write!(f, "Over Time"),
        }
    }
}

/// Method for measuring progress toward completion.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum ProgressMethod {
    /// Output methods (units produced, milestones, surveys).
    #[default]
    Output,
    /// Input methods (costs incurred, resources consumed, time elapsed).
    Input,
    /// Straight-line method (for series with similar effort).
    StraightLine,
}

impl std::fmt::Display for ProgressMethod {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Output => write!(f, "Output Method"),
            Self::Input => write!(f, "Input Method"),
            Self::StraightLine => write!(f, "Straight-Line"),
        }
    }
}

/// Variable consideration component.
///
/// Represents amounts that can vary based on future events (discounts,
/// rebates, refunds, incentives, etc.).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VariableConsideration {
    /// Unique identifier.
    pub vc_id: Uuid,

    /// Parent contract ID.
    pub contract_id: Uuid,

    /// Type of variable consideration.
    pub vc_type: VariableConsiderationType,

    /// Estimated amount (expected value or most likely amount).
    #[serde(with = "datasynth_core::serde_decimal")]
    pub estimated_amount: Decimal,

    /// Constrained amount included in transaction price.
    #[serde(with = "datasynth_core::serde_decimal")]
    pub constrained_amount: Decimal,

    /// Estimation method used.
    pub estimation_method: EstimationMethod,

    /// Probability that estimate is reliable.
    #[serde(with = "datasynth_core::serde_decimal")]
    pub probability: Decimal,

    /// Description of the variable component.
    pub description: String,

    /// Resolution date (when uncertainty is resolved).
    pub resolution_date: Option<NaiveDate>,

    /// Actual amount (after resolution).
    #[serde(default, with = "datasynth_core::serde_decimal::option")]
    pub actual_amount: Option<Decimal>,
}

impl VariableConsideration {
    /// Create a new variable consideration component.
    pub fn new(
        contract_id: Uuid,
        vc_type: VariableConsiderationType,
        estimated_amount: Decimal,
        description: impl Into<String>,
    ) -> Self {
        Self {
            vc_id: Uuid::now_v7(),
            contract_id,
            vc_type,
            estimated_amount,
            constrained_amount: estimated_amount,
            estimation_method: EstimationMethod::ExpectedValue,
            probability: Decimal::from(80),
            description: description.into(),
            resolution_date: None,
            actual_amount: None,
        }
    }

    /// Apply constraint to prevent significant revenue reversal.
    pub fn apply_constraint(&mut self, constraint_threshold: Decimal) {
        // Constrain to amount highly probable not to result in reversal
        self.constrained_amount = self.estimated_amount * constraint_threshold;
    }
}

/// Type of variable consideration.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum VariableConsiderationType {
    /// Volume or trade discount.
    Discount,
    /// Rebate based on volume or other criteria.
    Rebate,
    /// Right of return (reduces transaction price).
    RightOfReturn,
    /// Performance bonus or incentive.
    IncentiveBonus,
    /// Penalty for non-performance.
    Penalty,
    /// Price concession.
    PriceConcession,
    /// Royalty based on sales or usage.
    Royalty,
    /// Contingent payment.
    ContingentPayment,
}

impl std::fmt::Display for VariableConsiderationType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Discount => write!(f, "Discount"),
            Self::Rebate => write!(f, "Rebate"),
            Self::RightOfReturn => write!(f, "Right of Return"),
            Self::IncentiveBonus => write!(f, "Incentive Bonus"),
            Self::Penalty => write!(f, "Penalty"),
            Self::PriceConcession => write!(f, "Price Concession"),
            Self::Royalty => write!(f, "Royalty"),
            Self::ContingentPayment => write!(f, "Contingent Payment"),
        }
    }
}

/// Method for estimating variable consideration.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum EstimationMethod {
    /// Expected value (probability-weighted average).
    #[default]
    ExpectedValue,
    /// Most likely amount (single most likely outcome).
    MostLikelyAmount,
}

/// Material right granted to customer.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MaterialRight {
    /// Type of material right.
    pub right_type: MaterialRightType,

    /// Standalone selling price of the right.
    #[serde(with = "datasynth_core::serde_decimal")]
    pub standalone_selling_price: Decimal,

    /// Exercise probability.
    #[serde(with = "datasynth_core::serde_decimal")]
    pub exercise_probability: Decimal,

    /// Expiration date.
    pub expiration_date: Option<NaiveDate>,
}

/// Type of material right.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MaterialRightType {
    /// Option to renew at discount.
    RenewalOption,
    /// Loyalty points or customer rewards.
    LoyaltyPoints,
    /// Free or discounted future products/services.
    FutureDiscount,
}

/// Contract modification record.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContractModification {
    /// Modification identifier.
    pub modification_id: Uuid,

    /// Date of modification.
    pub modification_date: NaiveDate,

    /// Type of modification treatment.
    pub treatment: ModificationTreatment,

    /// Change in transaction price.
    #[serde(with = "datasynth_core::serde_decimal")]
    pub price_change: Decimal,

    /// Description of modification.
    pub description: String,
}

/// Treatment for contract modifications.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ModificationTreatment {
    /// Treat as separate contract.
    SeparateContract,
    /// Terminate existing and create new contract.
    TerminateAndCreate,
    /// Cumulative catch-up adjustment.
    CumulativeCatchUp,
    /// Prospective adjustment.
    Prospective,
}

/// Revenue recognition schedule entry.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RevenueRecognitionEntry {
    /// Parent contract ID.
    pub contract_id: Uuid,

    /// Performance obligation ID.
    pub obligation_id: Uuid,

    /// Recognition period (month end date).
    pub period_date: NaiveDate,

    /// Revenue recognized in this period.
    #[serde(with = "datasynth_core::serde_decimal")]
    pub revenue_amount: Decimal,

    /// Cumulative revenue recognized.
    #[serde(with = "datasynth_core::serde_decimal")]
    pub cumulative_revenue: Decimal,

    /// Deferred revenue balance.
    #[serde(with = "datasynth_core::serde_decimal")]
    pub deferred_revenue_balance: Decimal,

    /// Contract asset balance.
    #[serde(with = "datasynth_core::serde_decimal")]
    pub contract_asset_balance: Decimal,

    /// Progress percentage at period end.
    #[serde(with = "datasynth_core::serde_decimal")]
    pub progress_percent: Decimal,

    /// Journal entry reference.
    pub journal_entry_id: Option<Uuid>,
}

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

    #[test]
    fn test_contract_creation() {
        let contract = CustomerContract::new(
            "CUST001",
            "Acme Corp",
            "1000",
            NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(),
            dec!(100000),
            "USD",
            AccountingFramework::UsGaap,
        );

        assert_eq!(contract.customer_id, "CUST001");
        assert_eq!(contract.transaction_price, dec!(100000));
        assert_eq!(contract.status, ContractStatus::Active);
        assert!(contract.performance_obligations.is_empty());
    }

    #[test]
    fn test_performance_obligation() {
        let contract_id = Uuid::now_v7();
        let mut po = PerformanceObligation::new(
            contract_id,
            1,
            "Software License",
            ObligationType::License,
            SatisfactionPattern::PointInTime,
            dec!(50000),
        );

        po.allocated_price = dec!(50000);
        po.update_progress(dec!(100), NaiveDate::from_ymd_opt(2024, 3, 31).unwrap());

        assert!(po.is_satisfied());
        assert_eq!(po.revenue_recognized, dec!(50000));
        assert_eq!(po.deferred_revenue, dec!(0));
    }

    #[test]
    fn test_over_time_recognition() {
        let contract_id = Uuid::now_v7();
        let mut po = PerformanceObligation::new(
            contract_id,
            1,
            "Consulting Services",
            ObligationType::Service,
            SatisfactionPattern::OverTime,
            dec!(120000),
        );

        po.allocated_price = dec!(120000);

        // 25% complete
        po.update_progress(dec!(25), NaiveDate::from_ymd_opt(2024, 1, 31).unwrap());
        assert_eq!(po.revenue_recognized, dec!(30000));
        assert_eq!(po.deferred_revenue, dec!(90000));

        // 50% complete
        po.update_progress(dec!(50), NaiveDate::from_ymd_opt(2024, 2, 29).unwrap());
        assert_eq!(po.revenue_recognized, dec!(60000));
        assert_eq!(po.deferred_revenue, dec!(60000));
    }

    #[test]
    fn test_variable_consideration_constraint() {
        let contract_id = Uuid::now_v7();
        let mut vc = VariableConsideration::new(
            contract_id,
            VariableConsiderationType::Rebate,
            dec!(10000),
            "Volume rebate",
        );

        vc.apply_constraint(dec!(0.80));
        assert_eq!(vc.constrained_amount, dec!(8000));
    }
}