datasynth-generators 5.33.1

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
//! C2 (#157) Piece 1 — project a closing trial balance onto next-period
//! opening balances.
//!
//! Multi-period generation needs Year N+1's opening positions to come
//! from Year N's closing TB. Three carry rules apply:
//!
//! - **Balance-sheet accounts** (`Asset`, `ContraAsset`, `Liability`,
//!   `ContraLiability`, `Equity`, `ContraEquity`) carry their closing
//!   `debit_balance` / `credit_balance` straight into Year N+1's opening.
//! - **P&L accounts** (`Revenue`, `Expense`) **do not** carry — they
//!   are zeroed in Year N+1 (every period starts with zero earnings).
//!   Their net effect is absorbed into Retained Earnings instead.
//! - **Retained Earnings** absorbs the period's net income. Concretely,
//!   the closing RE balance plus `Σ(P&L credit - P&L debit)` becomes
//!   Year N+1's opening RE balance.
//!
//! This is exactly the year-end "close" entry every real general
//! ledger posts as the last move of each year. We synthesize it
//! here from the closing TB rather than emitting an explicit JE,
//! because the consumer (`ShardContext.opening_balances` in
//! `datasynth-runtime`) wants the projected positions, not the
//! posting that produced them.
//!
//! See `docs/design/2026-05-27-c2-multi-period-design.md` for the
//! broader C2 plan.

use datasynth_core::framework_accounts::FrameworkAccounts;
use datasynth_core::models::balance::{AccountType, EntityOpeningBalance, TrialBalance};
use rust_decimal::Decimal;

/// Project a closing trial balance onto next-period opening balances.
///
/// `framework` selects the Retained-Earnings account code (US GAAP
/// uses `"3200"`; SKR03/04 uses `"2970"`; IFRS uses different
/// numbering still). Pass the same framework string the orchestrator
/// uses for the prior period — mismatches mean net income lands in
/// the wrong account.
///
/// The output:
/// - Contains one row per BS account from the closing TB.
/// - Excludes all Revenue / Expense lines (they zero out).
/// - The Retained Earnings row carries closing RE plus the period's
///   net income (positive RE → credit, negative → debit; one-sided).
/// - If the closing TB has no Retained Earnings row but a non-zero
///   net income, inserts one with the framework's RE account code.
pub fn project_closing_to_opening(
    closing_tb: &TrialBalance,
    framework: &str,
) -> Vec<EntityOpeningBalance> {
    let fa = FrameworkAccounts::for_framework(framework);
    let re_account = fa.retained_earnings.clone();

    let mut net_income = Decimal::ZERO;
    let mut openings: Vec<EntityOpeningBalance> = Vec::with_capacity(closing_tb.lines.len());
    let mut re_idx: Option<usize> = None;

    for line in &closing_tb.lines {
        match line.account_type {
            // Balance-sheet → carry as-is.
            AccountType::Asset
            | AccountType::ContraAsset
            | AccountType::Liability
            | AccountType::ContraLiability
            | AccountType::Equity
            | AccountType::ContraEquity => {
                if line.account_code == re_account {
                    re_idx = Some(openings.len());
                }
                openings.push(EntityOpeningBalance {
                    account_code: line.account_code.clone(),
                    account_type: line.account_type,
                    debit: line.debit_balance,
                    credit: line.credit_balance,
                });
            }
            // P&L → accumulate signed contribution to net income.
            // For credit-normal Revenue: (credit - debit) is positive
            // when revenue exceeded reversals. For debit-normal
            // Expense: (credit - debit) is *negative* by the same
            // sign, so summing both yields net income directly.
            AccountType::Revenue | AccountType::Expense => {
                net_income += line.credit_balance - line.debit_balance;
            }
        }
    }

    // Absorb net income into Retained Earnings.
    if !net_income.is_zero() {
        match re_idx {
            Some(i) => {
                // Combine prior credit-side balance with net income, then
                // normalise to one-sided so the EntityOpeningBalance row
                // stays well-formed (we never want debit > 0 AND credit > 0
                // on the same opening row).
                let net = openings[i].credit - openings[i].debit + net_income;
                if net >= Decimal::ZERO {
                    openings[i].credit = net;
                    openings[i].debit = Decimal::ZERO;
                } else {
                    openings[i].debit = -net;
                    openings[i].credit = Decimal::ZERO;
                }
            }
            None => {
                // No RE row in the closing TB but the period generated
                // earnings — synthesize the row.
                let (debit, credit) = if net_income >= Decimal::ZERO {
                    (Decimal::ZERO, net_income)
                } else {
                    (-net_income, Decimal::ZERO)
                };
                openings.push(EntityOpeningBalance {
                    account_code: re_account,
                    account_type: AccountType::Equity,
                    debit,
                    credit,
                });
            }
        }
    }

    openings
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::{NaiveDate, NaiveDateTime};
    use datasynth_core::models::balance::{
        AccountCategory, TrialBalanceLine, TrialBalanceStatus, TrialBalanceType,
    };
    use rust_decimal_macros::dec;
    use std::collections::HashMap;

    /// Pin the US-GAAP retained-earnings account this module's tests
    /// reference. Sourced from
    /// `datasynth_core::accounts::equity_accounts::RETAINED_EARNINGS`
    /// so a future re-numbering can't silently break the tests.
    const RE_US_GAAP: &str = datasynth_core::accounts::equity_accounts::RETAINED_EARNINGS;

    fn tb_line(
        code: &str,
        account_type: AccountType,
        category: AccountCategory,
        debit: Decimal,
        credit: Decimal,
    ) -> TrialBalanceLine {
        TrialBalanceLine {
            account_code: code.to_string(),
            account_description: format!("Test {code}"),
            category,
            account_type,
            opening_balance: Decimal::ZERO,
            period_debits: Decimal::ZERO,
            period_credits: Decimal::ZERO,
            closing_balance: debit - credit,
            debit_balance: debit,
            credit_balance: credit,
            cost_center: None,
            profit_center: None,
        }
    }

    fn make_tb(lines: Vec<TrialBalanceLine>) -> TrialBalance {
        let total_debits: Decimal = lines.iter().map(|l| l.debit_balance).sum();
        let total_credits: Decimal = lines.iter().map(|l| l.credit_balance).sum();
        TrialBalance {
            trial_balance_id: "TB001".into(),
            company_code: "C001".into(),
            company_name: None,
            as_of_date: NaiveDate::from_ymd_opt(2026, 12, 31).unwrap(),
            fiscal_year: 2026,
            fiscal_period: 12,
            currency: "USD".into(),
            balance_type: TrialBalanceType::PostClosing,
            lines,
            total_debits,
            total_credits,
            is_balanced: total_debits == total_credits,
            out_of_balance: total_debits - total_credits,
            is_equation_valid: true,
            equation_difference: Decimal::ZERO,
            category_summary: HashMap::new(),
            created_at: NaiveDateTime::default(),
            created_by: "test".into(),
            approved_by: None,
            approved_at: None,
            status: TrialBalanceStatus::Final,
        }
    }

    #[test]
    fn bs_accounts_carry_pl_accounts_do_not() {
        // Mini TB: cash + AP + revenue + cogs (no RE — net income
        // should synthesize one).
        let lines = vec![
            tb_line(
                "1000",
                AccountType::Asset,
                AccountCategory::CurrentAssets,
                dec!(10_000),
                dec!(0),
            ),
            tb_line(
                "2000",
                AccountType::Liability,
                AccountCategory::CurrentLiabilities,
                dec!(0),
                dec!(4_000),
            ),
            tb_line(
                "4000",
                AccountType::Revenue,
                AccountCategory::Revenue,
                dec!(0),
                dec!(8_000),
            ),
            tb_line(
                "5000",
                AccountType::Expense,
                AccountCategory::OperatingExpenses,
                dec!(2_000),
                dec!(0),
            ),
        ];
        let tb = make_tb(lines);

        let openings = project_closing_to_opening(&tb, "us_gaap");

        // Should have 3 rows: 1000 (asset), 2000 (liability), 3300
        // (synthesized RE) — Revenue + Expense excluded.
        assert_eq!(openings.len(), 3);
        let codes: Vec<&str> = openings.iter().map(|o| o.account_code.as_str()).collect();
        assert!(codes.contains(&"1000"));
        assert!(codes.contains(&"2000"));
        assert!(codes.contains(&RE_US_GAAP));
        assert!(!codes.contains(&"4000"), "revenue must not carry");
        assert!(!codes.contains(&"5000"), "expense must not carry");
    }

    #[test]
    fn retained_earnings_absorbs_net_income() {
        // Net income = (8000 revenue credit) + (-2000 expense debit
        // contribution) = (0 - 8000) wait, net_income = Σ(credit -
        // debit) over P&L. For 4000 (credit 8000): credit - debit =
        // 8000. For 5000 (debit 2000): credit - debit = -2000. Sum =
        // 6000 net income.
        let lines = vec![
            tb_line(
                "1000",
                AccountType::Asset,
                AccountCategory::CurrentAssets,
                dec!(20_000),
                dec!(0),
            ),
            tb_line(
                "2000",
                AccountType::Liability,
                AccountCategory::CurrentLiabilities,
                dec!(0),
                dec!(4_000),
            ),
            tb_line(
                "3000",
                AccountType::Equity,
                AccountCategory::Equity,
                dec!(0),
                dec!(10_000),
            ),
            tb_line(
                RE_US_GAAP,
                AccountType::Equity,
                AccountCategory::Equity,
                dec!(0),
                dec!(0),
            ),
            tb_line(
                "4000",
                AccountType::Revenue,
                AccountCategory::Revenue,
                dec!(0),
                dec!(8_000),
            ),
            tb_line(
                "5000",
                AccountType::Expense,
                AccountCategory::OperatingExpenses,
                dec!(2_000),
                dec!(0),
            ),
        ];
        let tb = make_tb(lines);

        let openings = project_closing_to_opening(&tb, "us_gaap");

        let re = openings
            .iter()
            .find(|o| o.account_code == RE_US_GAAP)
            .expect("RE row missing");
        assert_eq!(
            re.credit,
            dec!(6000),
            "RE should absorb +6000 net income (8000 revenue - 2000 expense)"
        );
        assert_eq!(re.debit, dec!(0));
    }

    #[test]
    fn opening_balance_is_balanced_after_close() {
        // A balanced closing TB must yield a balanced opening
        // balance after the close. Build a balanced TB:
        //   Assets    = 20_000
        //   Liab      =  4_000
        //   Common Eq = 10_000
        //   RE        =      0 (will absorb net income)
        //   Revenue   =  8_000 (credit)
        //   Expense   =  2_000 (debit)
        // Total DR = 20_000 + 2_000 = 22_000
        // Total CR = 4_000 + 10_000 + 8_000 = 22_000. ✓
        let lines = vec![
            tb_line(
                "1000",
                AccountType::Asset,
                AccountCategory::CurrentAssets,
                dec!(20_000),
                dec!(0),
            ),
            tb_line(
                "2000",
                AccountType::Liability,
                AccountCategory::CurrentLiabilities,
                dec!(0),
                dec!(4_000),
            ),
            tb_line(
                "3000",
                AccountType::Equity,
                AccountCategory::Equity,
                dec!(0),
                dec!(10_000),
            ),
            tb_line(
                RE_US_GAAP,
                AccountType::Equity,
                AccountCategory::Equity,
                dec!(0),
                dec!(0),
            ),
            tb_line(
                "4000",
                AccountType::Revenue,
                AccountCategory::Revenue,
                dec!(0),
                dec!(8_000),
            ),
            tb_line(
                "5000",
                AccountType::Expense,
                AccountCategory::OperatingExpenses,
                dec!(2_000),
                dec!(0),
            ),
        ];
        let tb = make_tb(lines);
        assert!(tb.is_balanced, "test fixture must be balanced");

        let openings = project_closing_to_opening(&tb, "us_gaap");

        // After close: Σ(debit) and Σ(credit) over openings must be equal.
        let total_dr: Decimal = openings.iter().map(|o| o.debit).sum();
        let total_cr: Decimal = openings.iter().map(|o| o.credit).sum();
        assert_eq!(
            total_dr, total_cr,
            "openings unbalanced: DR={total_dr} CR={total_cr} (Σ(BS lines + RE-with-net-income) must net to zero)"
        );

        // And the accounting equation Assets = Liabilities + Equity
        // (using net_balance which sign-aware sums each account type).
        let assets: Decimal = openings
            .iter()
            .filter(|o| {
                matches!(
                    o.account_type,
                    AccountType::Asset | AccountType::ContraAsset
                )
            })
            .map(|o| o.net_balance())
            .sum();
        let liab: Decimal = openings
            .iter()
            .filter(|o| {
                matches!(
                    o.account_type,
                    AccountType::Liability | AccountType::ContraLiability
                )
            })
            .map(|o| o.net_balance())
            .sum();
        let equity: Decimal = openings
            .iter()
            .filter(|o| {
                matches!(
                    o.account_type,
                    AccountType::Equity | AccountType::ContraEquity
                )
            })
            .map(|o| o.net_balance())
            .sum();
        assert_eq!(
            assets,
            liab + equity,
            "accounting equation broken: Assets={assets} Liabilities={liab} Equity={equity}"
        );
    }

    #[test]
    fn loss_year_pushes_retained_earnings_to_debit() {
        // Loss = expense exceeds revenue.
        let lines = vec![
            tb_line(
                "1000",
                AccountType::Asset,
                AccountCategory::CurrentAssets,
                dec!(5_000),
                dec!(0),
            ),
            tb_line(
                "2000",
                AccountType::Liability,
                AccountCategory::CurrentLiabilities,
                dec!(0),
                dec!(2_000),
            ),
            tb_line(
                "3000",
                AccountType::Equity,
                AccountCategory::Equity,
                dec!(0),
                dec!(3_000),
            ),
            tb_line(
                RE_US_GAAP,
                AccountType::Equity,
                AccountCategory::Equity,
                dec!(0),
                dec!(500),
            ), // small positive RE entering
            tb_line(
                "4000",
                AccountType::Revenue,
                AccountCategory::Revenue,
                dec!(0),
                dec!(1_000),
            ),
            tb_line(
                "5000",
                AccountType::Expense,
                AccountCategory::OperatingExpenses,
                dec!(2_500),
                dec!(0),
            ),
        ];
        let tb = make_tb(lines);

        let openings = project_closing_to_opening(&tb, "us_gaap");

        // Net income = (1000) + (-2500) = -1500 (a 1 500 loss).
        // Closing RE = 500 credit; after absorbing loss = 500 - 1500
        // = -1000 → goes to debit side.
        let re = openings
            .iter()
            .find(|o| o.account_code == RE_US_GAAP)
            .expect("RE missing");
        assert_eq!(
            re.debit,
            dec!(1000),
            "RE should land on debit side after loss exceeds prior credit"
        );
        assert_eq!(re.credit, dec!(0));
    }

    #[test]
    fn zero_net_income_leaves_re_untouched() {
        // Revenue = expense → net income 0. RE row stays exactly as-is.
        let lines = vec![
            tb_line(
                "1000",
                AccountType::Asset,
                AccountCategory::CurrentAssets,
                dec!(10_000),
                dec!(0),
            ),
            tb_line(
                RE_US_GAAP,
                AccountType::Equity,
                AccountCategory::Equity,
                dec!(0),
                dec!(10_000),
            ),
            tb_line(
                "4000",
                AccountType::Revenue,
                AccountCategory::Revenue,
                dec!(0),
                dec!(3_000),
            ),
            tb_line(
                "5000",
                AccountType::Expense,
                AccountCategory::OperatingExpenses,
                dec!(3_000),
                dec!(0),
            ),
        ];
        let tb = make_tb(lines);

        let openings = project_closing_to_opening(&tb, "us_gaap");

        let re = openings
            .iter()
            .find(|o| o.account_code == RE_US_GAAP)
            .expect("RE missing");
        assert_eq!(
            re.credit,
            dec!(10_000),
            "RE should be unchanged when net income is zero"
        );
        assert_eq!(re.debit, dec!(0));
    }
}