datasynth-generators 2.2.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
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
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
//! Notes to financial statements generator.
//!
//! Assembles 8–13 standard notes from available generation outputs.
//! Each note is template-driven: if the underlying data is not present,
//! that note is simply omitted.  The notes produced follow the ordering
//! and content requirements of IAS 1 Presentation of Financial Statements
//! and, where applicable, ASC 235 / the relevant topic-specific US GAAP
//! guidance.
//!
//! # Notes generated (when data is available)
//!
//! 1. Significant Accounting Policies
//! 2. Revenue Recognition (ASC 606 / IFRS 15)
//! 3. Property, Plant & Equipment
//! 4. Income Taxes (IAS 12 / ASC 740)
//! 5. Provisions & Contingencies (IAS 37 / ASC 450)
//! 6. Related Party Transactions (IAS 24 / ASC 850)
//! 7. Subsequent Events (IAS 10 / ASC 855)
//! 8. Employee Benefits / Pensions (IAS 19 / ASC 715)

use chrono::NaiveDate;
use datasynth_core::models::{
    FinancialStatementNote, NoteCategory, NoteSection, NoteTable, NoteTableValue,
};
use datasynth_core::utils::seeded_rng;
use rand::Rng;
use rand_chacha::ChaCha8Rng;
use rust_decimal::Decimal;

// ---------------------------------------------------------------------------
// Input context
// ---------------------------------------------------------------------------

/// Summary data drawn from the overall generation result, passed into the
/// notes generator so it can decide which notes to include and what numbers
/// to populate them with.
#[derive(Debug, Clone, Default)]
pub struct NotesGeneratorContext {
    /// Entity / company code for which notes are prepared.
    pub entity_code: String,
    /// Reporting framework name (e.g. "IFRS", "US GAAP").
    pub framework: String,
    /// Fiscal period descriptor (e.g. "FY2024").
    pub period: String,
    /// Period end date.
    pub period_end: NaiveDate,
    /// Reporting currency code (e.g. "USD").
    pub currency: String,

    // ---- Revenue ----
    /// Number of customer contracts recognised during the period.
    pub revenue_contract_count: usize,
    /// Total revenue amount.
    pub revenue_amount: Option<Decimal>,
    /// Average number of performance obligations per contract.
    pub avg_obligations_per_contract: Option<Decimal>,

    // ---- PP&E ----
    /// Total gross fixed asset carrying amount.
    pub total_ppe_gross: Option<Decimal>,
    /// Accumulated depreciation on fixed assets.
    pub accumulated_depreciation: Option<Decimal>,

    // ---- Taxes ----
    /// Statutory tax rate (e.g. 0.21 for 21 %).
    pub statutory_tax_rate: Option<Decimal>,
    /// Effective tax rate actually incurred.
    pub effective_tax_rate: Option<Decimal>,
    /// Deferred tax asset balance.
    pub deferred_tax_asset: Option<Decimal>,
    /// Deferred tax liability balance.
    pub deferred_tax_liability: Option<Decimal>,

    // ---- Provisions ----
    /// Number of provisions recognised.
    pub provision_count: usize,
    /// Total carrying value of all provisions.
    pub total_provisions: Option<Decimal>,

    // ---- Related parties ----
    /// Number of related party transactions identified.
    pub related_party_transaction_count: usize,
    /// Total value of related party transactions.
    pub related_party_total_value: Option<Decimal>,

    // ---- Subsequent events ----
    /// Number of subsequent events identified.
    pub subsequent_event_count: usize,
    /// Number of adjusting subsequent events.
    pub adjusting_event_count: usize,

    // ---- Pensions ----
    /// Number of defined benefit plans.
    pub pension_plan_count: usize,
    /// Total DBO at period end.
    pub total_dbo: Option<Decimal>,
    /// Total plan assets at fair value.
    pub total_plan_assets: Option<Decimal>,
}

// ---------------------------------------------------------------------------
// Generator
// ---------------------------------------------------------------------------

/// Generator for notes to the financial statements.
pub struct NotesGenerator {
    rng: ChaCha8Rng,
}

impl NotesGenerator {
    /// Create a new generator with the given seed.
    pub fn new(seed: u64) -> Self {
        Self {
            rng: seeded_rng(seed, 0x4E07), // discriminator for "NOTE"
        }
    }

    /// Generate all applicable notes for a single entity/period.
    ///
    /// Returns between 0 and 8 notes depending on which data is present in
    /// the provided context.  Note numbers are assigned sequentially starting
    /// from 1.
    pub fn generate(&mut self, ctx: &NotesGeneratorContext) -> Vec<FinancialStatementNote> {
        let mut notes: Vec<FinancialStatementNote> = Vec::new();

        // Note 1 — Significant Accounting Policies (always generated)
        notes.push(self.note_accounting_policies(ctx));

        // Note 2 — Revenue Recognition
        if ctx.revenue_contract_count > 0 || ctx.revenue_amount.is_some() {
            notes.push(self.note_revenue_recognition(ctx));
        }

        // Note 3 — Property, Plant & Equipment
        if ctx.total_ppe_gross.is_some() {
            notes.push(self.note_property_plant_equipment(ctx));
        }

        // Note 4 — Income Taxes
        if ctx.statutory_tax_rate.is_some() || ctx.deferred_tax_asset.is_some() {
            notes.push(self.note_income_taxes(ctx));
        }

        // Note 5 — Provisions & Contingencies
        if ctx.provision_count > 0 || ctx.total_provisions.is_some() {
            notes.push(self.note_provisions(ctx));
        }

        // Note 6 — Related Party Transactions
        if ctx.related_party_transaction_count > 0 {
            notes.push(self.note_related_parties(ctx));
        }

        // Note 7 — Subsequent Events
        if ctx.subsequent_event_count > 0 {
            notes.push(self.note_subsequent_events(ctx));
        }

        // Note 8 — Employee Benefits (Pensions)
        if ctx.pension_plan_count > 0 || ctx.total_dbo.is_some() {
            notes.push(self.note_employee_benefits(ctx));
        }

        // Assign sequential note numbers
        for (i, note) in notes.iter_mut().enumerate() {
            note.note_number = (i + 1) as u32;
        }

        notes
    }

    // -----------------------------------------------------------------------
    // Note builders
    // -----------------------------------------------------------------------

    fn note_accounting_policies(&mut self, ctx: &NotesGeneratorContext) -> FinancialStatementNote {
        let framework = &ctx.framework;
        let narrative = format!(
            "The financial statements of {} have been prepared in accordance with {} \
             on a going concern basis, using the historical cost convention except where \
             otherwise stated.  The financial statements are presented in {} and all \
             values are rounded to the nearest unit unless otherwise indicated.  \
             Critical accounting estimates and judgements are described in the relevant \
             notes below.",
            ctx.entity_code, framework, ctx.currency
        );

        let key_policies = [
            ("Revenue Recognition", format!("Revenue is recognised in accordance with {} 15 (Revenue from Contracts with Customers). The five-step model is applied to identify contracts, performance obligations, and transaction prices.", if framework.to_lowercase().contains("ifrs") { "IFRS" } else { "ASC 606" })),
            ("Property, Plant & Equipment", "PP&E is stated at cost less accumulated depreciation and impairment losses. Depreciation is computed on a straight-line basis over the estimated useful lives of the assets.".to_string()),
            ("Income Taxes", "Income tax expense comprises current and deferred tax. Deferred tax is recognised using the balance sheet liability method.".to_string()),
            ("Provisions", "A provision is recognised when the entity has a present obligation as a result of a past event, and it is probable that an outflow of resources will be required to settle the obligation.".to_string()),
        ];

        let table = NoteTable {
            caption: "Summary of Key Accounting Policies".to_string(),
            headers: vec![
                "Policy Area".to_string(),
                "Accounting Treatment".to_string(),
            ],
            rows: key_policies
                .iter()
                .map(|(area, treatment)| {
                    vec![
                        NoteTableValue::Text(area.to_string()),
                        NoteTableValue::Text(treatment.clone()),
                    ]
                })
                .collect(),
        };

        FinancialStatementNote {
            note_number: 0, // renumbered later
            title: "Significant Accounting Policies".to_string(),
            category: NoteCategory::AccountingPolicy,
            content_sections: vec![NoteSection {
                heading: "Basis of Preparation".to_string(),
                narrative,
                tables: vec![table],
            }],
            cross_references: Vec::new(),
        }
    }

    fn note_revenue_recognition(&mut self, ctx: &NotesGeneratorContext) -> FinancialStatementNote {
        let contract_count = ctx.revenue_contract_count;
        let revenue_str = ctx
            .revenue_amount
            .map(|a| format!("{} {:.0}", ctx.currency, a))
            .unwrap_or_else(|| "N/A".to_string());
        let avg_oblig = ctx
            .avg_obligations_per_contract
            .map(|v| format!("{:.1}", v))
            .unwrap_or_else(|| "N/A".to_string());

        let narrative = format!(
            "Revenue is recognised when (or as) performance obligations are satisfied by \
             transferring control of a promised good or service to the customer.  During \
             {} the entity entered into {} revenue contracts with an average of {} \
             performance obligation(s) per contract.  Total revenue recognised was {}.",
            ctx.period, contract_count, avg_oblig, revenue_str
        );

        let rows = vec![
            vec![
                NoteTableValue::Text("Number of contracts".to_string()),
                NoteTableValue::Text(contract_count.to_string()),
            ],
            vec![
                NoteTableValue::Text("Revenue recognised".to_string()),
                NoteTableValue::Text(revenue_str),
            ],
            vec![
                NoteTableValue::Text("Avg. performance obligations per contract".to_string()),
                NoteTableValue::Text(avg_oblig),
            ],
        ];

        FinancialStatementNote {
            note_number: 0,
            title: "Revenue Recognition".to_string(),
            category: NoteCategory::StandardSpecific,
            content_sections: vec![NoteSection {
                heading: "Revenue from Contracts with Customers".to_string(),
                narrative,
                tables: vec![NoteTable {
                    caption: "Revenue Disaggregation Summary".to_string(),
                    headers: vec!["Metric".to_string(), "Value".to_string()],
                    rows,
                }],
            }],
            cross_references: vec!["Note 1 — Accounting Policies".to_string()],
        }
    }

    fn note_property_plant_equipment(
        &mut self,
        ctx: &NotesGeneratorContext,
    ) -> FinancialStatementNote {
        let gross = ctx.total_ppe_gross.unwrap_or(Decimal::ZERO);
        let acc_dep = ctx.accumulated_depreciation.unwrap_or(Decimal::ZERO).abs();
        let net = gross - acc_dep;

        // Generate 2–4 asset category rows
        let num_categories = self.rng.random_range(2usize..=4);
        let category_names = [
            "Land & Buildings",
            "Machinery & Equipment",
            "Motor Vehicles",
            "IT Equipment & Fixtures",
        ];
        let mut rows = Vec::new();
        for name in category_names.iter().take(num_categories) {
            let share = Decimal::new(self.rng.random_range(10i64..=40), 2); // 0.10–0.40
            rows.push(vec![
                NoteTableValue::Text(name.to_string()),
                NoteTableValue::Amount(gross * share),
                NoteTableValue::Amount(acc_dep * share),
                NoteTableValue::Amount((gross - acc_dep) * share),
            ]);
        }
        // Totals row
        rows.push(vec![
            NoteTableValue::Text("Total".to_string()),
            NoteTableValue::Amount(gross),
            NoteTableValue::Amount(acc_dep),
            NoteTableValue::Amount(net),
        ]);

        let narrative = format!(
            "Property, plant and equipment is stated at cost less accumulated depreciation \
             and any recognised impairment loss.  At {} the gross carrying amount was \
             {currency} {gross:.0} with accumulated depreciation of {currency} {acc_dep:.0}, \
             resulting in a net book value of {currency} {net:.0}.",
            ctx.period_end,
            currency = ctx.currency,
        );

        FinancialStatementNote {
            note_number: 0,
            title: "Property, Plant & Equipment".to_string(),
            category: NoteCategory::DetailDisclosure,
            content_sections: vec![NoteSection {
                heading: "PP&E Roll-Forward".to_string(),
                narrative,
                tables: vec![NoteTable {
                    caption: format!("PP&E Carrying Amounts at {}", ctx.period_end),
                    headers: vec![
                        "Category".to_string(),
                        format!("Gross ({currency})", currency = ctx.currency),
                        format!("Acc. Dep. ({currency})", currency = ctx.currency),
                        format!("Net ({currency})", currency = ctx.currency),
                    ],
                    rows,
                }],
            }],
            cross_references: Vec::new(),
        }
    }

    fn note_income_taxes(&mut self, ctx: &NotesGeneratorContext) -> FinancialStatementNote {
        let statutory = ctx
            .statutory_tax_rate
            .unwrap_or_else(|| Decimal::new(21, 2)); // default 21%
        let effective = ctx.effective_tax_rate.unwrap_or_else(|| {
            let adj = Decimal::new(self.rng.random_range(-5i64..=5), 2);
            statutory + adj
        });
        let dta = ctx.deferred_tax_asset.unwrap_or(Decimal::ZERO);
        let dtl = ctx.deferred_tax_liability.unwrap_or(Decimal::ZERO);

        let narrative = format!(
            "The entity is subject to income taxes in multiple jurisdictions.  The statutory \
             tax rate applicable to the primary jurisdiction is {statutory:.1}%.  \
             The effective tax rate for {period} was {effective:.1}%, reflecting permanent \
             differences and the utilisation of deferred tax balances.  At period end a \
             deferred tax asset of {currency} {dta:.0} and a deferred tax liability of \
             {currency} {dtl:.0} were recognised.",
            statutory = statutory * Decimal::new(100, 0),
            period = ctx.period,
            effective = effective * Decimal::new(100, 0),
            currency = ctx.currency,
        );

        let rows = vec![
            vec![
                NoteTableValue::Text("Statutory tax rate".to_string()),
                NoteTableValue::Percentage(statutory),
            ],
            vec![
                NoteTableValue::Text("Effective tax rate".to_string()),
                NoteTableValue::Percentage(effective),
            ],
            vec![
                NoteTableValue::Text("Deferred tax asset".to_string()),
                NoteTableValue::Amount(dta),
            ],
            vec![
                NoteTableValue::Text("Deferred tax liability".to_string()),
                NoteTableValue::Amount(dtl),
            ],
            vec![
                NoteTableValue::Text("Net deferred tax position".to_string()),
                NoteTableValue::Amount(dta - dtl),
            ],
        ];

        FinancialStatementNote {
            note_number: 0,
            title: "Income Taxes".to_string(),
            category: NoteCategory::StandardSpecific,
            content_sections: vec![NoteSection {
                heading: "Tax Charge and Deferred Tax Balances".to_string(),
                narrative,
                tables: vec![NoteTable {
                    caption: "Income Tax Summary".to_string(),
                    headers: vec!["Item".to_string(), "Value".to_string()],
                    rows,
                }],
            }],
            cross_references: Vec::new(),
        }
    }

    fn note_provisions(&mut self, ctx: &NotesGeneratorContext) -> FinancialStatementNote {
        let count = ctx.provision_count;
        let total = ctx
            .total_provisions
            .unwrap_or_else(|| Decimal::new(self.rng.random_range(50_000i64..=5_000_000), 0));

        let narrative = format!(
            "Provisions are recognised when the entity has a present obligation \
             (legal or constructive) as a result of a past event, it is probable that \
             an outflow of resources embodying economic benefits will be required to settle \
             the obligation, and a reliable estimate can be made of the amount.  At {} a \
             total of {} provision(s) were recognised with a combined carrying value of \
             {} {:.0}.",
            ctx.period_end, count, ctx.currency, total
        );

        let provision_types = [
            ("Warranty",),
            ("Legal Claims",),
            ("Restructuring",),
            ("Environmental",),
        ];
        let num_rows = count.min(provision_types.len()).max(2);
        let per_provision = if num_rows > 0 {
            total / Decimal::new(num_rows as i64, 0)
        } else {
            total
        };
        let mut rows: Vec<Vec<NoteTableValue>> = provision_types[..num_rows]
            .iter()
            .map(|(name,)| {
                vec![
                    NoteTableValue::Text(name.to_string()),
                    NoteTableValue::Amount(per_provision),
                ]
            })
            .collect();
        rows.push(vec![
            NoteTableValue::Text("Total".to_string()),
            NoteTableValue::Amount(total),
        ]);

        FinancialStatementNote {
            note_number: 0,
            title: "Provisions & Contingencies".to_string(),
            category: NoteCategory::Contingency,
            content_sections: vec![NoteSection {
                heading: "Movement in Provisions".to_string(),
                narrative,
                tables: vec![NoteTable {
                    caption: format!("Provisions at {} ({})", ctx.period_end, ctx.currency),
                    headers: vec![
                        "Provision Type".to_string(),
                        format!("Carrying Amount ({})", ctx.currency),
                    ],
                    rows,
                }],
            }],
            cross_references: vec!["Note 1 — Accounting Policies".to_string()],
        }
    }

    fn note_related_parties(&mut self, ctx: &NotesGeneratorContext) -> FinancialStatementNote {
        let count = ctx.related_party_transaction_count;
        let total = ctx
            .related_party_total_value
            .unwrap_or_else(|| Decimal::new(self.rng.random_range(100_000i64..=10_000_000), 0));

        let narrative = format!(
            "During {} the entity engaged in {} related party transaction(s) with a \
             combined value of {} {:.0}.  All transactions were conducted on an arm's-length \
             basis and have been approved by the board of directors.",
            ctx.period, count, ctx.currency, total
        );

        let rows = vec![
            vec![
                NoteTableValue::Text("Number of transactions".to_string()),
                NoteTableValue::Text(count.to_string()),
            ],
            vec![
                NoteTableValue::Text("Total transaction value".to_string()),
                NoteTableValue::Amount(total),
            ],
        ];

        FinancialStatementNote {
            note_number: 0,
            title: "Related Party Transactions".to_string(),
            category: NoteCategory::RelatedParty,
            content_sections: vec![NoteSection {
                heading: "Transactions with Related Parties".to_string(),
                narrative,
                tables: vec![NoteTable {
                    caption: "Related Party Summary".to_string(),
                    headers: vec!["Item".to_string(), "Value".to_string()],
                    rows,
                }],
            }],
            cross_references: Vec::new(),
        }
    }

    fn note_subsequent_events(&mut self, ctx: &NotesGeneratorContext) -> FinancialStatementNote {
        let count = ctx.subsequent_event_count;
        let adj = ctx.adjusting_event_count;
        let non_adj = count.saturating_sub(adj);

        let narrative = format!(
            "Management has evaluated events and transactions that occurred after the \
             balance sheet date of {} through the financial statement issuance date.  \
             {} event(s) were identified: {} adjusting event(s) and {} non-adjusting \
             event(s).  Non-adjusting events are disclosed but do not result in \
             adjustments to the financial statements.",
            ctx.period_end, count, adj, non_adj
        );

        let rows = vec![
            vec![
                NoteTableValue::Text("Total subsequent events".to_string()),
                NoteTableValue::Text(count.to_string()),
            ],
            vec![
                NoteTableValue::Text("Adjusting (IAS 10.8 / ASC 855)".to_string()),
                NoteTableValue::Text(adj.to_string()),
            ],
            vec![
                NoteTableValue::Text("Non-adjusting — disclosed only".to_string()),
                NoteTableValue::Text(non_adj.to_string()),
            ],
        ];

        FinancialStatementNote {
            note_number: 0,
            title: "Subsequent Events".to_string(),
            category: NoteCategory::SubsequentEvent,
            content_sections: vec![NoteSection {
                heading: "Events after the Reporting Period".to_string(),
                narrative,
                tables: vec![NoteTable {
                    caption: "Subsequent Events Summary".to_string(),
                    headers: vec!["Category".to_string(), "Count".to_string()],
                    rows,
                }],
            }],
            cross_references: Vec::new(),
        }
    }

    fn note_employee_benefits(&mut self, ctx: &NotesGeneratorContext) -> FinancialStatementNote {
        let plan_count = ctx.pension_plan_count;
        let dbo = ctx
            .total_dbo
            .unwrap_or_else(|| Decimal::new(self.rng.random_range(500_000i64..=50_000_000), 0));
        let assets = ctx
            .total_plan_assets
            .unwrap_or_else(|| dbo * Decimal::new(85, 2)); // funded at ~85%
        let funded_status = assets - dbo;

        let narrative = format!(
            "The entity operates {} defined benefit pension plan(s) for qualifying employees.  \
             The defined benefit obligation (DBO) is measured using the Projected Unit Credit \
             method.  At {} the DBO totalled {} {:.0}, while plan assets at fair value \
             amounted to {} {:.0}, resulting in a net funded status of {} {:.0}.",
            plan_count,
            ctx.period_end,
            ctx.currency,
            dbo,
            ctx.currency,
            assets,
            ctx.currency,
            funded_status
        );

        let rows = vec![
            vec![
                NoteTableValue::Text("Number of defined benefit plans".to_string()),
                NoteTableValue::Text(plan_count.to_string()),
            ],
            vec![
                NoteTableValue::Text("Defined Benefit Obligation (DBO)".to_string()),
                NoteTableValue::Amount(dbo),
            ],
            vec![
                NoteTableValue::Text("Plan assets at fair value".to_string()),
                NoteTableValue::Amount(assets),
            ],
            vec![
                NoteTableValue::Text("Net funded status".to_string()),
                NoteTableValue::Amount(funded_status),
            ],
        ];

        FinancialStatementNote {
            note_number: 0,
            title: "Employee Benefits".to_string(),
            category: NoteCategory::StandardSpecific,
            content_sections: vec![NoteSection {
                heading: "Defined Benefit Pension Plans".to_string(),
                narrative,
                tables: vec![NoteTable {
                    caption: format!(
                        "Pension Plan Summary at {} ({})",
                        ctx.period_end, ctx.currency
                    ),
                    headers: vec!["Item".to_string(), "Value".to_string()],
                    rows,
                }],
            }],
            cross_references: vec!["Note 1 — Accounting Policies".to_string()],
        }
    }
}

// ---------------------------------------------------------------------------
// Enhanced notes context + method
// ---------------------------------------------------------------------------

/// Extended context carrying data from v2.2/v2.3 modules (manufacturing,
/// treasury, provisions) used to populate 4 supplementary notes.
#[derive(Debug, Clone, Default)]
pub struct EnhancedNotesContext {
    /// Entity code (matches the primary `NotesGeneratorContext`).
    pub entity_code: String,
    /// Fiscal period descriptor (e.g. "FY2024").
    pub period: String,
    /// Reporting currency code (e.g. "USD").
    pub currency: String,

    // ---- Inventory (v2.2 manufacturing) ----
    /// Carrying value of finished goods inventory.
    pub finished_goods_value: Decimal,
    /// Carrying value of work-in-progress inventory.
    pub wip_value: Decimal,
    /// Carrying value of raw materials inventory.
    pub raw_materials_value: Decimal,

    // ---- Debt (v2.3 treasury) ----
    /// Debt instruments as `(type, principal, maturity_date_str)` tuples.
    pub debt_instruments: Vec<(String, Decimal, String)>,

    // ---- Hedge accounting (v2.3 treasury) ----
    /// Total number of hedging relationships.
    pub hedge_count: usize,
    /// Number of relationships assessed as effective.
    pub effective_hedges: usize,
    /// Aggregate notional amount across all hedges.
    pub total_notional: Decimal,
    /// Aggregate fair value (mark-to-market) across all hedges.
    pub total_fair_value: Decimal,

    // ---- Provisions rollforward (v2.2 warranty + v2.3 ECL) ----
    /// Provision movements as `(type, opening, additions, closing)` tuples.
    pub provision_movements: Vec<(String, Decimal, Decimal, Decimal)>,
}

impl NotesGenerator {
    /// Generate 4 supplementary notes backed by v2.2/v2.3 data.
    ///
    /// Notes are numbered starting from `starting_note_number` so they do not
    /// collide with the 8 standard notes produced by [`NotesGenerator::generate`].
    pub fn generate_enhanced_notes(
        &mut self,
        context: &EnhancedNotesContext,
        starting_note_number: u32,
    ) -> Vec<FinancialStatementNote> {
        let mut notes = vec![
            self.note_inventories(context),
            self.note_borrowings(context),
            self.note_hedge_accounting(context),
            self.note_provisions_rollforward(context),
        ];

        // Assign sequential note numbers starting from the given offset
        for (i, note) in notes.iter_mut().enumerate() {
            note.note_number = starting_note_number + i as u32;
        }

        notes
    }

    // -----------------------------------------------------------------------
    // Enhanced note builders
    // -----------------------------------------------------------------------

    fn note_inventories(&mut self, ctx: &EnhancedNotesContext) -> FinancialStatementNote {
        let fg = ctx.finished_goods_value;
        let wip = ctx.wip_value;
        let rm = ctx.raw_materials_value;
        let total = fg + wip + rm;

        let narrative = format!(
            "Inventories are stated at the lower of cost and net realisable value.  \
             Cost is determined using the weighted-average cost method.  At the end \
             of {} the carrying amounts were: finished goods {} {fg:.0}, \
             work in progress {} {wip:.0}, and raw materials {} {rm:.0}, \
             giving a total of {} {total:.0}.",
            ctx.period, ctx.currency, ctx.currency, ctx.currency, ctx.currency,
        );

        let rows = vec![
            vec![
                NoteTableValue::Text("Finished Goods".to_string()),
                NoteTableValue::Amount(fg),
            ],
            vec![
                NoteTableValue::Text("Work in Progress".to_string()),
                NoteTableValue::Amount(wip),
            ],
            vec![
                NoteTableValue::Text("Raw Materials".to_string()),
                NoteTableValue::Amount(rm),
            ],
            vec![
                NoteTableValue::Text("Total".to_string()),
                NoteTableValue::Amount(total),
            ],
        ];

        FinancialStatementNote {
            note_number: 0,
            title: "Inventories".to_string(),
            category: NoteCategory::DetailDisclosure,
            content_sections: vec![NoteSection {
                heading: "Inventory Breakdown by Category".to_string(),
                narrative,
                tables: vec![NoteTable {
                    caption: format!(
                        "Inventory Carrying Amounts — {} ({})",
                        ctx.period, ctx.currency
                    ),
                    headers: vec!["Category".to_string(), format!("Amount ({})", ctx.currency)],
                    rows,
                }],
            }],
            cross_references: Vec::new(),
        }
    }

    fn note_borrowings(&mut self, ctx: &EnhancedNotesContext) -> FinancialStatementNote {
        let total_principal: Decimal = ctx
            .debt_instruments
            .iter()
            .map(|(_, principal, _)| *principal)
            .sum();

        let narrative = format!(
            "Borrowings are initially recognised at fair value less directly attributable \
             transaction costs and subsequently measured at amortised cost.  At {} the \
             entity had {} debt instrument(s) outstanding with a combined principal of \
             {} {total_principal:.0}.",
            ctx.period,
            ctx.debt_instruments.len(),
            ctx.currency,
        );

        let rows: Vec<Vec<NoteTableValue>> = ctx
            .debt_instruments
            .iter()
            .map(|(debt_type, principal, maturity)| {
                vec![
                    NoteTableValue::Text(debt_type.clone()),
                    NoteTableValue::Amount(*principal),
                    NoteTableValue::Text(maturity.clone()),
                ]
            })
            .collect();

        FinancialStatementNote {
            note_number: 0,
            title: "Borrowings and Debt Instruments".to_string(),
            category: NoteCategory::DetailDisclosure,
            content_sections: vec![NoteSection {
                heading: "Debt Maturity Schedule".to_string(),
                narrative,
                tables: vec![NoteTable {
                    caption: format!(
                        "Debt Instruments Outstanding — {} ({})",
                        ctx.period, ctx.currency
                    ),
                    headers: vec![
                        "Type".to_string(),
                        format!("Principal ({})", ctx.currency),
                        "Maturity Date".to_string(),
                    ],
                    rows,
                }],
            }],
            cross_references: Vec::new(),
        }
    }

    fn note_hedge_accounting(&mut self, ctx: &EnhancedNotesContext) -> FinancialStatementNote {
        let effectiveness_rate = if ctx.hedge_count > 0 {
            Decimal::new(ctx.effective_hedges as i64, 0) / Decimal::new(ctx.hedge_count as i64, 0)
        } else {
            Decimal::ZERO
        };

        let effectiveness_pct = effectiveness_rate * Decimal::new(100, 0);

        let narrative = format!(
            "The entity applies hedge accounting in accordance with IFRS 9 / ASC 815 \
             where the hedging relationship meets the qualifying criteria.  At {} \
             {} hedging relationship(s) were designated, of which {} were assessed as \
             effective ({effectiveness_pct:.1}%).  The aggregate notional amount was \
             {} {:.0} with a net fair value of {} {:.0}.",
            ctx.period,
            ctx.hedge_count,
            ctx.effective_hedges,
            ctx.currency,
            ctx.total_notional,
            ctx.currency,
            ctx.total_fair_value,
        );

        let kv_pairs = vec![
            (
                "Total hedging relationships".to_string(),
                ctx.hedge_count.to_string(),
            ),
            (
                "Effective hedges".to_string(),
                ctx.effective_hedges.to_string(),
            ),
            (
                format!("Total notional ({})", ctx.currency),
                format!("{:.0}", ctx.total_notional),
            ),
            (
                format!("Total fair value ({})", ctx.currency),
                format!("{:.0}", ctx.total_fair_value),
            ),
            (
                "Effectiveness rate".to_string(),
                format!("{effectiveness_pct:.1}%"),
            ),
        ];

        let rows: Vec<Vec<NoteTableValue>> = kv_pairs
            .into_iter()
            .map(|(k, v)| vec![NoteTableValue::Text(k), NoteTableValue::Text(v)])
            .collect();

        FinancialStatementNote {
            note_number: 0,
            title: "Hedge Accounting".to_string(),
            category: NoteCategory::DetailDisclosure,
            content_sections: vec![NoteSection {
                heading: "Hedge Effectiveness and Notional Amounts".to_string(),
                narrative,
                tables: vec![NoteTable {
                    caption: format!("Hedge Accounting Summary — {}", ctx.period),
                    headers: vec!["Item".to_string(), "Value".to_string()],
                    rows,
                }],
            }],
            cross_references: Vec::new(),
        }
    }

    fn note_provisions_rollforward(
        &mut self,
        ctx: &EnhancedNotesContext,
    ) -> FinancialStatementNote {
        let total_opening: Decimal = ctx
            .provision_movements
            .iter()
            .map(|(_, opening, _, _)| *opening)
            .sum();
        let total_additions: Decimal = ctx
            .provision_movements
            .iter()
            .map(|(_, _, additions, _)| *additions)
            .sum();
        let total_closing: Decimal = ctx
            .provision_movements
            .iter()
            .map(|(_, _, _, closing)| *closing)
            .sum();

        let narrative = format!(
            "The following table sets out the movement in provisions during {}.  \
             Provisions are recognised when it is probable that an outflow of economic \
             resources will be required.  Opening balances totalled {} {total_opening:.0}, \
             additions during the period were {} {total_additions:.0}, and closing \
             balances stood at {} {total_closing:.0}.",
            ctx.period, ctx.currency, ctx.currency, ctx.currency,
        );

        let mut rows: Vec<Vec<NoteTableValue>> = ctx
            .provision_movements
            .iter()
            .map(|(prov_type, opening, additions, closing)| {
                vec![
                    NoteTableValue::Text(prov_type.clone()),
                    NoteTableValue::Amount(*opening),
                    NoteTableValue::Amount(*additions),
                    NoteTableValue::Amount(*closing),
                ]
            })
            .collect();

        // Totals row
        rows.push(vec![
            NoteTableValue::Text("Total".to_string()),
            NoteTableValue::Amount(total_opening),
            NoteTableValue::Amount(total_additions),
            NoteTableValue::Amount(total_closing),
        ]);

        FinancialStatementNote {
            note_number: 0,
            title: "Provisions Rollforward".to_string(),
            category: NoteCategory::DetailDisclosure,
            content_sections: vec![NoteSection {
                heading: "Movement in Provisions".to_string(),
                narrative,
                tables: vec![NoteTable {
                    caption: format!("Provisions Rollforward — {} ({})", ctx.period, ctx.currency),
                    headers: vec![
                        "Provision Type".to_string(),
                        format!("Opening ({})", ctx.currency),
                        format!("Additions ({})", ctx.currency),
                        format!("Closing ({})", ctx.currency),
                    ],
                    rows,
                }],
            }],
            cross_references: vec!["Note 1 — Accounting Policies".to_string()],
        }
    }
}

// ---------------------------------------------------------------------------
// Unit tests
// ---------------------------------------------------------------------------

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

    fn default_context() -> NotesGeneratorContext {
        NotesGeneratorContext {
            entity_code: "C001".to_string(),
            framework: "IFRS".to_string(),
            period: "FY2024".to_string(),
            period_end: NaiveDate::from_ymd_opt(2024, 12, 31).unwrap(),
            currency: "USD".to_string(),
            revenue_contract_count: 50,
            revenue_amount: Some(Decimal::new(10_000_000, 0)),
            avg_obligations_per_contract: Some(Decimal::new(2, 0)),
            total_ppe_gross: Some(Decimal::new(5_000_000, 0)),
            accumulated_depreciation: Some(Decimal::new(1_500_000, 0)),
            statutory_tax_rate: Some(Decimal::new(21, 2)),
            effective_tax_rate: Some(Decimal::new(24, 2)),
            deferred_tax_asset: Some(Decimal::new(200_000, 0)),
            deferred_tax_liability: Some(Decimal::new(50_000, 0)),
            provision_count: 4,
            total_provisions: Some(Decimal::new(800_000, 0)),
            related_party_transaction_count: 12,
            related_party_total_value: Some(Decimal::new(2_500_000, 0)),
            subsequent_event_count: 3,
            adjusting_event_count: 1,
            pension_plan_count: 2,
            total_dbo: Some(Decimal::new(15_000_000, 0)),
            total_plan_assets: Some(Decimal::new(13_000_000, 0)),
        }
    }

    #[test]
    fn test_at_least_three_notes_generated() {
        let mut gen = NotesGenerator::new(42);
        let ctx = default_context();
        let notes = gen.generate(&ctx);
        assert!(
            notes.len() >= 3,
            "Expected at least 3 notes, got {}",
            notes.len()
        );
    }

    #[test]
    fn test_note_numbers_are_sequential() {
        let mut gen = NotesGenerator::new(42);
        let ctx = default_context();
        let notes = gen.generate(&ctx);
        for (i, note) in notes.iter().enumerate() {
            assert_eq!(
                note.note_number,
                (i + 1) as u32,
                "Note at index {} has number {}, expected {}",
                i,
                note.note_number,
                i + 1
            );
        }
    }

    #[test]
    fn test_every_note_has_title_and_content() {
        let mut gen = NotesGenerator::new(42);
        let ctx = default_context();
        let notes = gen.generate(&ctx);
        for note in &notes {
            assert!(
                !note.title.is_empty(),
                "Note {} has an empty title",
                note.note_number
            );
            assert!(
                !note.content_sections.is_empty(),
                "Note '{}' has no content sections",
                note.title
            );
        }
    }

    #[test]
    fn test_accounting_policy_note_always_first() {
        let mut gen = NotesGenerator::new(42);
        let ctx = default_context();
        let notes = gen.generate(&ctx);
        assert!(!notes.is_empty());
        assert_eq!(notes[0].note_number, 1);
        assert!(
            notes[0].title.contains("Accounting Policies"),
            "First note should be Accounting Policies, got '{}'",
            notes[0].title
        );
    }

    #[test]
    fn test_no_revenue_note_when_no_revenue_data() {
        let mut gen = NotesGenerator::new(42);
        let ctx = NotesGeneratorContext {
            entity_code: "C001".to_string(),
            framework: "US GAAP".to_string(),
            period: "FY2024".to_string(),
            period_end: NaiveDate::from_ymd_opt(2024, 12, 31).unwrap(),
            currency: "USD".to_string(),
            ..NotesGeneratorContext::default()
        };
        let notes = gen.generate(&ctx);
        // Should still have at least the accounting policies note
        assert!(!notes.is_empty());
        let has_revenue_note = notes.iter().any(|n| n.title.contains("Revenue"));
        assert!(
            !has_revenue_note,
            "Should not generate revenue note when no data"
        );
    }

    #[test]
    fn test_deterministic_output() {
        let ctx = default_context();
        let notes1 = NotesGenerator::new(42).generate(&ctx);
        let notes2 = NotesGenerator::new(42).generate(&ctx);
        assert_eq!(notes1.len(), notes2.len());
        for (a, b) in notes1.iter().zip(notes2.iter()) {
            assert_eq!(a.note_number, b.note_number);
            assert_eq!(a.title, b.title);
        }
    }
}