datasynth-generators 2.4.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
//! Year-end closing entry generator.

use chrono::NaiveDate;
use rust_decimal::Decimal;
use rust_decimal_macros::dec;
use std::collections::HashMap;

use datasynth_core::accounts::{equity_accounts, tax_accounts};
use datasynth_core::models::{
    JournalEntry, JournalEntryLine, TaxAdjustment, TaxProvisionInput, TaxProvisionResult,
    YearEndClosingSpec,
};

/// Configuration for year-end closing.
#[derive(Debug, Clone)]
pub struct YearEndCloseConfig {
    /// Income summary account.
    pub income_summary_account: String,
    /// Retained earnings account.
    pub retained_earnings_account: String,
    /// Dividend declared account.
    pub dividend_account: String,
    /// Current tax payable account.
    pub current_tax_payable_account: String,
    /// Deferred tax liability account.
    pub deferred_tax_liability_account: String,
    /// Deferred tax asset account.
    pub deferred_tax_asset_account: String,
    /// Tax expense account.
    pub tax_expense_account: String,
    /// Statutory tax rate.
    pub statutory_tax_rate: Decimal,
}

impl Default for YearEndCloseConfig {
    fn default() -> Self {
        Self {
            income_summary_account: equity_accounts::INCOME_SUMMARY.to_string(),
            retained_earnings_account: equity_accounts::RETAINED_EARNINGS.to_string(),
            dividend_account: equity_accounts::DIVIDENDS_PAID.to_string(),
            current_tax_payable_account: tax_accounts::SALES_TAX_PAYABLE.to_string(),
            deferred_tax_liability_account: tax_accounts::DEFERRED_TAX_LIABILITY.to_string(),
            deferred_tax_asset_account: tax_accounts::DEFERRED_TAX_ASSET.to_string(),
            tax_expense_account: tax_accounts::TAX_EXPENSE.to_string(),
            statutory_tax_rate: dec!(21),
        }
    }
}

impl From<&datasynth_core::FrameworkAccounts> for YearEndCloseConfig {
    fn from(fa: &datasynth_core::FrameworkAccounts) -> Self {
        Self {
            income_summary_account: fa.income_summary.clone(),
            retained_earnings_account: fa.retained_earnings.clone(),
            dividend_account: fa.dividends_paid.clone(),
            current_tax_payable_account: fa.sales_tax_payable.clone(),
            deferred_tax_liability_account: fa.deferred_tax_liability.clone(),
            deferred_tax_asset_account: fa.deferred_tax_asset.clone(),
            tax_expense_account: fa.tax_expense.clone(),
            ..Default::default()
        }
    }
}

/// Generator for year-end closing entries.
pub struct YearEndCloseGenerator {
    config: YearEndCloseConfig,
    entry_counter: u64,
}

impl YearEndCloseGenerator {
    /// Creates a new year-end close generator.
    pub fn new(config: YearEndCloseConfig) -> Self {
        Self {
            config,
            entry_counter: 0,
        }
    }

    /// Generates the complete year-end closing entries.
    pub fn generate_year_end_close(
        &mut self,
        company_code: &str,
        fiscal_year: i32,
        trial_balance: &HashMap<String, Decimal>,
        spec: &YearEndClosingSpec,
    ) -> YearEndCloseResult {
        let closing_date =
            NaiveDate::from_ymd_opt(fiscal_year, 12, 31).expect("valid year-end date");

        let mut result = YearEndCloseResult {
            company_code: company_code.to_string(),
            fiscal_year,
            closing_entries: Vec::new(),
            total_revenue_closed: Decimal::ZERO,
            total_expense_closed: Decimal::ZERO,
            net_income: Decimal::ZERO,
            retained_earnings_impact: Decimal::ZERO,
        };

        // Step 1: Close revenue accounts to income summary
        let (revenue_je, revenue_total) =
            self.close_revenue_accounts(company_code, closing_date, trial_balance, spec);
        result.total_revenue_closed = revenue_total;
        result.closing_entries.push(revenue_je);

        // Step 2: Close expense accounts to income summary
        let (expense_je, expense_total) =
            self.close_expense_accounts(company_code, closing_date, trial_balance, spec);
        result.total_expense_closed = expense_total;
        result.closing_entries.push(expense_je);

        // Step 3: Close income summary to retained earnings
        let net_income = revenue_total - expense_total;
        result.net_income = net_income;

        let income_summary_je = self.close_income_summary(company_code, closing_date, net_income);
        result.closing_entries.push(income_summary_je);

        // Step 4: Close dividends to retained earnings (if applicable)
        if let Some(dividend_account) = &spec.dividend_account {
            if let Some(dividend_balance) = trial_balance.get(dividend_account) {
                if *dividend_balance != Decimal::ZERO {
                    let dividend_je = self.close_dividends(
                        company_code,
                        closing_date,
                        *dividend_balance,
                        dividend_account,
                    );
                    result.closing_entries.push(dividend_je);
                    result.retained_earnings_impact = net_income - *dividend_balance;
                } else {
                    result.retained_earnings_impact = net_income;
                }
            } else {
                result.retained_earnings_impact = net_income;
            }
        } else {
            result.retained_earnings_impact = net_income;
        }

        result
    }

    /// Closes revenue accounts to income summary.
    fn close_revenue_accounts(
        &mut self,
        company_code: &str,
        closing_date: NaiveDate,
        trial_balance: &HashMap<String, Decimal>,
        spec: &YearEndClosingSpec,
    ) -> (JournalEntry, Decimal) {
        self.entry_counter += 1;
        let doc_number = format!("YECL-REV-{:08}", self.entry_counter);

        let mut je = JournalEntry::new_simple(
            doc_number.clone(),
            company_code.to_string(),
            closing_date,
            "Year-End Close: Revenue to Income Summary".to_string(),
        );

        let mut line_num = 1u32;
        let mut total_revenue = Decimal::ZERO;

        // Find all revenue accounts (accounts starting with prefixes in spec)
        for (account, balance) in trial_balance {
            let is_revenue = spec
                .revenue_accounts
                .iter()
                .any(|prefix| account.starts_with(prefix));

            if is_revenue && *balance != Decimal::ZERO {
                // Revenue accounts have credit balances, so debit to close
                je.add_line(JournalEntryLine {
                    line_number: line_num,
                    gl_account: account.clone(),
                    debit_amount: *balance,
                    reference: Some(doc_number.clone()),
                    text: Some("Year-end close".to_string()),
                    ..Default::default()
                });
                line_num += 1;
                total_revenue += *balance;
            }
        }

        // Credit Income Summary
        if total_revenue != Decimal::ZERO {
            je.add_line(JournalEntryLine {
                line_number: line_num,
                gl_account: spec.income_summary_account.clone(),
                credit_amount: total_revenue,
                reference: Some(doc_number.clone()),
                text: Some("Revenue closed".to_string()),
                ..Default::default()
            });
        }

        (je, total_revenue)
    }

    /// Closes expense accounts to income summary.
    fn close_expense_accounts(
        &mut self,
        company_code: &str,
        closing_date: NaiveDate,
        trial_balance: &HashMap<String, Decimal>,
        spec: &YearEndClosingSpec,
    ) -> (JournalEntry, Decimal) {
        self.entry_counter += 1;
        let doc_number = format!("YECL-EXP-{:08}", self.entry_counter);

        let mut je = JournalEntry::new_simple(
            doc_number.clone(),
            company_code.to_string(),
            closing_date,
            "Year-End Close: Expenses to Income Summary".to_string(),
        );

        let mut line_num = 1u32;
        let mut total_expenses = Decimal::ZERO;

        // Debit Income Summary first
        // We'll update this amount after calculating total expenses

        // Find all expense accounts
        let mut expense_lines = Vec::new();
        for (account, balance) in trial_balance {
            let is_expense = spec
                .expense_accounts
                .iter()
                .any(|prefix| account.starts_with(prefix));

            if is_expense && *balance != Decimal::ZERO {
                expense_lines.push((account.clone(), *balance));
                total_expenses += *balance;
            }
        }

        // Debit Income Summary
        if total_expenses != Decimal::ZERO {
            je.add_line(JournalEntryLine {
                line_number: line_num,
                gl_account: spec.income_summary_account.clone(),
                debit_amount: total_expenses,
                reference: Some(doc_number.clone()),
                text: Some("Expenses closed".to_string()),
                ..Default::default()
            });
            line_num += 1;
        }

        // Credit each expense account
        for (account, balance) in expense_lines {
            je.add_line(JournalEntryLine {
                line_number: line_num,
                gl_account: account,
                credit_amount: balance,
                reference: Some(doc_number.clone()),
                text: Some("Year-end close".to_string()),
                ..Default::default()
            });
            line_num += 1;
        }

        (je, total_expenses)
    }

    /// Closes income summary to retained earnings.
    fn close_income_summary(
        &mut self,
        company_code: &str,
        closing_date: NaiveDate,
        net_income: Decimal,
    ) -> JournalEntry {
        self.entry_counter += 1;
        let doc_number = format!("YECL-IS-{:08}", self.entry_counter);

        let mut je = JournalEntry::new_simple(
            doc_number.clone(),
            company_code.to_string(),
            closing_date,
            "Year-End Close: Income Summary to Retained Earnings".to_string(),
        );

        if net_income > Decimal::ZERO {
            // Profit: Debit Income Summary, Credit Retained Earnings
            je.add_line(JournalEntryLine {
                line_number: 1,
                gl_account: self.config.income_summary_account.clone(),
                debit_amount: net_income,
                reference: Some(doc_number.clone()),
                text: Some("Net income transfer".to_string()),
                ..Default::default()
            });

            je.add_line(JournalEntryLine {
                line_number: 2,
                gl_account: self.config.retained_earnings_account.clone(),
                credit_amount: net_income,
                reference: Some(doc_number.clone()),
                text: Some("Net income for year".to_string()),
                ..Default::default()
            });
        } else if net_income < Decimal::ZERO {
            // Loss: Debit Retained Earnings, Credit Income Summary
            let loss = net_income.abs();
            je.add_line(JournalEntryLine {
                line_number: 1,
                gl_account: self.config.retained_earnings_account.clone(),
                debit_amount: loss,
                reference: Some(doc_number.clone()),
                text: Some("Net loss for year".to_string()),
                ..Default::default()
            });

            je.add_line(JournalEntryLine {
                line_number: 2,
                gl_account: self.config.income_summary_account.clone(),
                credit_amount: loss,
                reference: Some(doc_number.clone()),
                text: Some("Net loss transfer".to_string()),
                ..Default::default()
            });
        }

        je
    }

    /// Closes dividends to retained earnings.
    fn close_dividends(
        &mut self,
        company_code: &str,
        closing_date: NaiveDate,
        dividend_amount: Decimal,
        dividend_account: &str,
    ) -> JournalEntry {
        self.entry_counter += 1;
        let doc_number = format!("YECL-DIV-{:08}", self.entry_counter);

        let mut je = JournalEntry::new_simple(
            doc_number.clone(),
            company_code.to_string(),
            closing_date,
            "Year-End Close: Dividends to Retained Earnings".to_string(),
        );

        // Debit Retained Earnings
        je.add_line(JournalEntryLine {
            line_number: 1,
            gl_account: self.config.retained_earnings_account.clone(),
            debit_amount: dividend_amount,
            reference: Some(doc_number.clone()),
            text: Some("Dividends declared".to_string()),
            ..Default::default()
        });

        // Credit Dividends
        je.add_line(JournalEntryLine {
            line_number: 2,
            gl_account: dividend_account.to_string(),
            credit_amount: dividend_amount,
            reference: Some(doc_number.clone()),
            text: Some("Dividends closed".to_string()),
            ..Default::default()
        });

        je
    }

    /// Generates tax provision entries.
    pub fn generate_tax_provision(
        &mut self,
        company_code: &str,
        fiscal_year: i32,
        pretax_income: Decimal,
        permanent_differences: Vec<TaxAdjustment>,
        temporary_differences: Vec<TaxAdjustment>,
    ) -> TaxProvisionGenerationResult {
        let closing_date =
            NaiveDate::from_ymd_opt(fiscal_year, 12, 31).expect("valid year-end date");

        let input = TaxProvisionInput {
            company_code: company_code.to_string(),
            fiscal_year,
            pretax_income,
            permanent_differences,
            temporary_differences,
            statutory_rate: self.config.statutory_tax_rate,
            tax_credits: Decimal::ZERO,
            prior_year_adjustment: Decimal::ZERO,
        };

        let provision = TaxProvisionResult::calculate(&input);

        // Generate journal entries
        let mut entries = Vec::new();

        // Entry 1: Current tax expense
        if provision.current_tax_expense != Decimal::ZERO {
            self.entry_counter += 1;
            let mut je = JournalEntry::new_simple(
                format!("TAX-CUR-{:08}", self.entry_counter),
                company_code.to_string(),
                closing_date,
                "Current Income Tax Expense".to_string(),
            );

            je.add_line(JournalEntryLine {
                line_number: 1,
                gl_account: self.config.tax_expense_account.clone(),
                debit_amount: provision.current_tax_expense,
                text: Some("Current tax provision".to_string()),
                ..Default::default()
            });

            je.add_line(JournalEntryLine {
                line_number: 2,
                gl_account: self.config.current_tax_payable_account.clone(),
                credit_amount: provision.current_tax_expense,
                ..Default::default()
            });

            entries.push(je);
        }

        // Entry 2: Deferred tax expense/benefit
        if provision.deferred_tax_expense != Decimal::ZERO {
            self.entry_counter += 1;
            let mut je = JournalEntry::new_simple(
                format!("TAX-DEF-{:08}", self.entry_counter),
                company_code.to_string(),
                closing_date,
                "Deferred Income Tax".to_string(),
            );

            if provision.deferred_tax_expense > Decimal::ZERO {
                // Deferred tax expense (increase in DTL or decrease in DTA)
                je.add_line(JournalEntryLine {
                    line_number: 1,
                    gl_account: self.config.tax_expense_account.clone(),
                    debit_amount: provision.deferred_tax_expense,
                    text: Some("Deferred tax expense".to_string()),
                    ..Default::default()
                });

                je.add_line(JournalEntryLine {
                    line_number: 2,
                    gl_account: self.config.deferred_tax_liability_account.clone(),
                    credit_amount: provision.deferred_tax_expense,
                    ..Default::default()
                });
            } else {
                // Deferred tax benefit (increase in DTA or decrease in DTL)
                let benefit = provision.deferred_tax_expense.abs();
                je.add_line(JournalEntryLine {
                    line_number: 1,
                    gl_account: self.config.deferred_tax_asset_account.clone(),
                    debit_amount: benefit,
                    text: Some("Deferred tax benefit".to_string()),
                    ..Default::default()
                });

                je.add_line(JournalEntryLine {
                    line_number: 2,
                    gl_account: self.config.tax_expense_account.clone(),
                    credit_amount: benefit,
                    ..Default::default()
                });
            }

            entries.push(je);
        }

        TaxProvisionGenerationResult {
            provision,
            journal_entries: entries,
        }
    }
}

/// Result of year-end closing.
#[derive(Debug, Clone)]
pub struct YearEndCloseResult {
    /// Company code.
    pub company_code: String,
    /// Fiscal year.
    pub fiscal_year: i32,
    /// Generated closing entries.
    pub closing_entries: Vec<JournalEntry>,
    /// Total revenue closed.
    pub total_revenue_closed: Decimal,
    /// Total expenses closed.
    pub total_expense_closed: Decimal,
    /// Net income (revenue - expenses).
    pub net_income: Decimal,
    /// Impact on retained earnings.
    pub retained_earnings_impact: Decimal,
}

impl YearEndCloseResult {
    /// Returns true if all entries are balanced.
    pub fn all_entries_balanced(&self) -> bool {
        self.closing_entries
            .iter()
            .all(datasynth_core::JournalEntry::is_balanced)
    }
}

/// Result of tax provision generation.
#[derive(Debug, Clone)]
pub struct TaxProvisionGenerationResult {
    /// Tax provision calculation result.
    pub provision: TaxProvisionResult,
    /// Generated journal entries.
    pub journal_entries: Vec<JournalEntry>,
}

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

    #[test]
    fn test_year_end_close() {
        let mut generator = YearEndCloseGenerator::new(YearEndCloseConfig::default());

        let mut trial_balance = HashMap::new();
        trial_balance.insert("4000".to_string(), dec!(500000)); // Revenue
        trial_balance.insert("4100".to_string(), dec!(50000)); // Other Revenue
        trial_balance.insert("5000".to_string(), dec!(300000)); // COGS
        trial_balance.insert("6000".to_string(), dec!(100000)); // Operating Expenses

        let spec = YearEndClosingSpec {
            company_code: "1000".to_string(),
            fiscal_year: 2024,
            revenue_accounts: vec!["4".to_string()],
            expense_accounts: vec!["5".to_string(), "6".to_string()],
            income_summary_account: "3500".to_string(),
            retained_earnings_account: "3300".to_string(),
            dividend_account: None,
        };

        let result = generator.generate_year_end_close("1000", 2024, &trial_balance, &spec);

        assert_eq!(result.total_revenue_closed, dec!(550000));
        assert_eq!(result.total_expense_closed, dec!(400000));
        assert_eq!(result.net_income, dec!(150000));
        assert!(result.all_entries_balanced());
    }

    #[test]
    fn test_tax_provision() {
        let mut generator = YearEndCloseGenerator::new(YearEndCloseConfig::default());

        let result = generator.generate_tax_provision(
            "1000",
            2024,
            dec!(1000000),
            vec![TaxAdjustment {
                description: "Non-deductible expenses".to_string(),
                amount: dec!(10000),
                is_addition: true,
            }],
            vec![],
        );

        assert!(result.provision.current_tax_expense > Decimal::ZERO);
        assert!(result.journal_entries.iter().all(|je| je.is_balanced()));
    }
}