1use std::collections::HashMap;
22use std::path::PathBuf;
23use std::sync::Arc;
24
25use chrono::{Datelike, NaiveDate};
26use indicatif::{MultiProgress, ProgressBar, ProgressStyle};
27use rand::SeedableRng;
28use serde::{Deserialize, Serialize};
29use tracing::{debug, info, warn};
30
31use datasynth_banking::{
32 models::{BankAccount, BankTransaction, BankingCustomer, CustomerName},
33 BankingOrchestratorBuilder,
34};
35use datasynth_config::schema::GeneratorConfig;
36use datasynth_core::error::{SynthError, SynthResult};
37use datasynth_core::models::audit::{
38 AuditEngagement, AuditEvidence, AuditFinding, ProfessionalJudgment, RiskAssessment, Workpaper,
39};
40use datasynth_core::models::sourcing::{
41 BidEvaluation, CatalogItem, ProcurementContract, RfxEvent, SourcingProject, SpendAnalysis,
42 SupplierBid, SupplierQualification, SupplierScorecard,
43};
44use datasynth_core::models::subledger::ap::APInvoice;
45use datasynth_core::models::subledger::ar::ARInvoice;
46use datasynth_core::models::*;
47use datasynth_core::{DegradationActions, DegradationLevel, ResourceGuard, ResourceGuardBuilder};
48use datasynth_fingerprint::{
49 io::FingerprintReader,
50 models::Fingerprint,
51 synthesis::{ConfigSynthesizer, CopulaGeneratorSpec, SynthesisOptions},
52};
53use datasynth_generators::{
54 AnomalyInjector,
56 AnomalyInjectorConfig,
57 AssetGenerator,
58 AuditEngagementGenerator,
60 BalanceTrackerConfig,
61 BankReconciliationGenerator,
63 BidEvaluationGenerator,
65 BidGenerator,
66 CatalogGenerator,
67 ChartOfAccountsGenerator,
69 ContractGenerator,
70 CustomerGenerator,
71 DataQualityConfig,
72 DataQualityInjector,
74 DataQualityStats,
75 DocumentFlowJeConfig,
77 DocumentFlowJeGenerator,
78 DocumentFlowLinker,
80 EmployeeGenerator,
81 EsgAnomalyLabel,
83 EvidenceGenerator,
84 FinancialStatementGenerator,
86 FindingGenerator,
87 JournalEntryGenerator,
88 JudgmentGenerator,
89 LatePaymentDistribution,
90 MaterialGenerator,
91 O2CDocumentChain,
92 O2CGenerator,
93 O2CGeneratorConfig,
94 O2CPaymentBehavior,
95 P2PDocumentChain,
96 P2PGenerator,
98 P2PGeneratorConfig,
99 P2PPaymentBehavior,
100 PaymentReference,
101 QualificationGenerator,
102 RfxGenerator,
103 RiskAssessmentGenerator,
104 RunningBalanceTracker,
106 ScorecardGenerator,
107 SourcingProjectGenerator,
108 SpendAnalysisGenerator,
109 ValidationError,
110 VendorGenerator,
112 WorkpaperGenerator,
113};
114use datasynth_graph::{
115 ApprovalGraphBuilder, ApprovalGraphConfig, BankingGraphBuilder, BankingGraphConfig,
116 PyGExportConfig, PyGExporter, TransactionGraphBuilder, TransactionGraphConfig,
117};
118use datasynth_ocpm::{
119 AuditDocuments, BankDocuments, BankReconDocuments, EventLogMetadata, H2rDocuments,
120 MfgDocuments, O2cDocuments, OcpmEventGenerator, OcpmEventLog, OcpmGeneratorConfig,
121 OcpmUuidFactory, P2pDocuments, S2cDocuments,
122};
123
124use datasynth_config::schema::{O2CFlowConfig, P2PFlowConfig};
125use datasynth_core::causal::{CausalGraph, CausalValidator, StructuralCausalModel};
126use datasynth_core::diffusion::{DiffusionBackend, DiffusionConfig, StatisticalDiffusionBackend};
127use datasynth_core::llm::MockLlmProvider;
128use datasynth_core::models::balance::{GeneratedOpeningBalance, IndustryType, OpeningBalanceSpec};
129use datasynth_core::models::documents::PaymentMethod;
130use datasynth_core::models::IndustrySector;
131use datasynth_generators::llm_enrichment::VendorLlmEnricher;
132
133fn convert_p2p_config(schema_config: &P2PFlowConfig) -> P2PGeneratorConfig {
139 let payment_behavior = &schema_config.payment_behavior;
140 let late_dist = &payment_behavior.late_payment_days_distribution;
141
142 P2PGeneratorConfig {
143 three_way_match_rate: schema_config.three_way_match_rate,
144 partial_delivery_rate: schema_config.partial_delivery_rate,
145 over_delivery_rate: 0.02, price_variance_rate: schema_config.price_variance_rate,
147 max_price_variance_percent: schema_config.max_price_variance_percent,
148 avg_days_po_to_gr: schema_config.average_po_to_gr_days,
149 avg_days_gr_to_invoice: schema_config.average_gr_to_invoice_days,
150 avg_days_invoice_to_payment: schema_config.average_invoice_to_payment_days,
151 payment_method_distribution: vec![
152 (PaymentMethod::BankTransfer, 0.60),
153 (PaymentMethod::Check, 0.25),
154 (PaymentMethod::Wire, 0.10),
155 (PaymentMethod::CreditCard, 0.05),
156 ],
157 early_payment_discount_rate: 0.30, payment_behavior: P2PPaymentBehavior {
159 late_payment_rate: payment_behavior.late_payment_rate,
160 late_payment_distribution: LatePaymentDistribution {
161 slightly_late_1_to_7: late_dist.slightly_late_1_to_7,
162 late_8_to_14: late_dist.late_8_to_14,
163 very_late_15_to_30: late_dist.very_late_15_to_30,
164 severely_late_31_to_60: late_dist.severely_late_31_to_60,
165 extremely_late_over_60: late_dist.extremely_late_over_60,
166 },
167 partial_payment_rate: payment_behavior.partial_payment_rate,
168 payment_correction_rate: payment_behavior.payment_correction_rate,
169 },
170 }
171}
172
173fn convert_o2c_config(schema_config: &O2CFlowConfig) -> O2CGeneratorConfig {
175 let payment_behavior = &schema_config.payment_behavior;
176
177 O2CGeneratorConfig {
178 credit_check_failure_rate: schema_config.credit_check_failure_rate,
179 partial_shipment_rate: schema_config.partial_shipment_rate,
180 avg_days_so_to_delivery: schema_config.average_so_to_delivery_days,
181 avg_days_delivery_to_invoice: schema_config.average_delivery_to_invoice_days,
182 avg_days_invoice_to_payment: schema_config.average_invoice_to_receipt_days,
183 late_payment_rate: 0.15, bad_debt_rate: schema_config.bad_debt_rate,
185 returns_rate: schema_config.return_rate,
186 cash_discount_take_rate: schema_config.cash_discount.taken_rate,
187 payment_method_distribution: vec![
188 (PaymentMethod::BankTransfer, 0.50),
189 (PaymentMethod::Check, 0.30),
190 (PaymentMethod::Wire, 0.15),
191 (PaymentMethod::CreditCard, 0.05),
192 ],
193 payment_behavior: O2CPaymentBehavior {
194 partial_payment_rate: payment_behavior.partial_payments.rate,
195 short_payment_rate: payment_behavior.short_payments.rate,
196 max_short_percent: payment_behavior.short_payments.max_short_percent,
197 on_account_rate: payment_behavior.on_account_payments.rate,
198 payment_correction_rate: payment_behavior.payment_corrections.rate,
199 avg_days_until_remainder: payment_behavior.partial_payments.avg_days_until_remainder,
200 },
201 }
202}
203
204#[derive(Debug, Clone)]
206pub struct PhaseConfig {
207 pub generate_master_data: bool,
209 pub generate_document_flows: bool,
211 pub generate_ocpm_events: bool,
213 pub generate_journal_entries: bool,
215 pub inject_anomalies: bool,
217 pub inject_data_quality: bool,
219 pub validate_balances: bool,
221 pub show_progress: bool,
223 pub vendors_per_company: usize,
225 pub customers_per_company: usize,
227 pub materials_per_company: usize,
229 pub assets_per_company: usize,
231 pub employees_per_company: usize,
233 pub p2p_chains: usize,
235 pub o2c_chains: usize,
237 pub generate_audit: bool,
239 pub audit_engagements: usize,
241 pub workpapers_per_engagement: usize,
243 pub evidence_per_workpaper: usize,
245 pub risks_per_engagement: usize,
247 pub findings_per_engagement: usize,
249 pub judgments_per_engagement: usize,
251 pub generate_banking: bool,
253 pub generate_graph_export: bool,
255 pub generate_sourcing: bool,
257 pub generate_bank_reconciliation: bool,
259 pub generate_financial_statements: bool,
261 pub generate_accounting_standards: bool,
263 pub generate_manufacturing: bool,
265 pub generate_sales_kpi_budgets: bool,
267 pub generate_tax: bool,
269 pub generate_esg: bool,
271 pub generate_intercompany: bool,
273}
274
275impl Default for PhaseConfig {
276 fn default() -> Self {
277 Self {
278 generate_master_data: true,
279 generate_document_flows: true,
280 generate_ocpm_events: false, generate_journal_entries: true,
282 inject_anomalies: false,
283 inject_data_quality: false, validate_balances: true,
285 show_progress: true,
286 vendors_per_company: 50,
287 customers_per_company: 100,
288 materials_per_company: 200,
289 assets_per_company: 50,
290 employees_per_company: 100,
291 p2p_chains: 100,
292 o2c_chains: 100,
293 generate_audit: false, audit_engagements: 5,
295 workpapers_per_engagement: 20,
296 evidence_per_workpaper: 5,
297 risks_per_engagement: 15,
298 findings_per_engagement: 8,
299 judgments_per_engagement: 10,
300 generate_banking: false, generate_graph_export: false, generate_sourcing: false, generate_bank_reconciliation: false, generate_financial_statements: false, generate_accounting_standards: false, generate_manufacturing: false, generate_sales_kpi_budgets: false, generate_tax: false, generate_esg: false, generate_intercompany: false, }
312 }
313}
314
315#[derive(Debug, Clone, Default)]
317pub struct MasterDataSnapshot {
318 pub vendors: Vec<Vendor>,
320 pub customers: Vec<Customer>,
322 pub materials: Vec<Material>,
324 pub assets: Vec<FixedAsset>,
326 pub employees: Vec<Employee>,
328}
329
330#[derive(Debug, Clone)]
332pub struct HypergraphExportInfo {
333 pub node_count: usize,
335 pub edge_count: usize,
337 pub hyperedge_count: usize,
339 pub output_path: PathBuf,
341}
342
343#[derive(Debug, Clone, Default)]
345pub struct DocumentFlowSnapshot {
346 pub p2p_chains: Vec<P2PDocumentChain>,
348 pub o2c_chains: Vec<O2CDocumentChain>,
350 pub purchase_orders: Vec<documents::PurchaseOrder>,
352 pub goods_receipts: Vec<documents::GoodsReceipt>,
354 pub vendor_invoices: Vec<documents::VendorInvoice>,
356 pub sales_orders: Vec<documents::SalesOrder>,
358 pub deliveries: Vec<documents::Delivery>,
360 pub customer_invoices: Vec<documents::CustomerInvoice>,
362 pub payments: Vec<documents::Payment>,
364}
365
366#[derive(Debug, Clone, Default)]
368pub struct SubledgerSnapshot {
369 pub ap_invoices: Vec<APInvoice>,
371 pub ar_invoices: Vec<ARInvoice>,
373 pub fa_records: Vec<datasynth_core::models::subledger::fa::FixedAssetRecord>,
375 pub inventory_positions: Vec<datasynth_core::models::subledger::inventory::InventoryPosition>,
377 pub inventory_movements: Vec<datasynth_core::models::subledger::inventory::InventoryMovement>,
379}
380
381#[derive(Debug, Clone, Default)]
383pub struct OcpmSnapshot {
384 pub event_log: Option<OcpmEventLog>,
386 pub event_count: usize,
388 pub object_count: usize,
390 pub case_count: usize,
392}
393
394#[derive(Debug, Clone, Default)]
396pub struct AuditSnapshot {
397 pub engagements: Vec<AuditEngagement>,
399 pub workpapers: Vec<Workpaper>,
401 pub evidence: Vec<AuditEvidence>,
403 pub risk_assessments: Vec<RiskAssessment>,
405 pub findings: Vec<AuditFinding>,
407 pub judgments: Vec<ProfessionalJudgment>,
409}
410
411#[derive(Debug, Clone, Default)]
413pub struct BankingSnapshot {
414 pub customers: Vec<BankingCustomer>,
416 pub accounts: Vec<BankAccount>,
418 pub transactions: Vec<BankTransaction>,
420 pub transaction_labels: Vec<datasynth_banking::labels::TransactionLabel>,
422 pub customer_labels: Vec<datasynth_banking::labels::CustomerLabel>,
424 pub account_labels: Vec<datasynth_banking::labels::AccountLabel>,
426 pub relationship_labels: Vec<datasynth_banking::labels::RelationshipLabel>,
428 pub narratives: Vec<datasynth_banking::labels::ExportedNarrative>,
430 pub suspicious_count: usize,
432 pub scenario_count: usize,
434}
435
436#[derive(Debug, Clone, Default, Serialize)]
438pub struct GraphExportSnapshot {
439 pub exported: bool,
441 pub graph_count: usize,
443 pub exports: HashMap<String, GraphExportInfo>,
445}
446
447#[derive(Debug, Clone, Serialize)]
449pub struct GraphExportInfo {
450 pub name: String,
452 pub format: String,
454 pub output_path: PathBuf,
456 pub node_count: usize,
458 pub edge_count: usize,
460}
461
462#[derive(Debug, Clone, Default)]
464pub struct SourcingSnapshot {
465 pub spend_analyses: Vec<SpendAnalysis>,
467 pub sourcing_projects: Vec<SourcingProject>,
469 pub qualifications: Vec<SupplierQualification>,
471 pub rfx_events: Vec<RfxEvent>,
473 pub bids: Vec<SupplierBid>,
475 pub bid_evaluations: Vec<BidEvaluation>,
477 pub contracts: Vec<ProcurementContract>,
479 pub catalog_items: Vec<CatalogItem>,
481 pub scorecards: Vec<SupplierScorecard>,
483}
484
485#[derive(Debug, Clone, Serialize, Deserialize)]
487pub struct PeriodTrialBalance {
488 pub fiscal_year: u16,
490 pub fiscal_period: u8,
492 pub period_start: NaiveDate,
494 pub period_end: NaiveDate,
496 pub entries: Vec<datasynth_generators::TrialBalanceEntry>,
498}
499
500#[derive(Debug, Clone, Default)]
502pub struct FinancialReportingSnapshot {
503 pub financial_statements: Vec<FinancialStatement>,
505 pub bank_reconciliations: Vec<BankReconciliation>,
507 pub trial_balances: Vec<PeriodTrialBalance>,
509}
510
511#[derive(Debug, Clone, Default)]
513pub struct HrSnapshot {
514 pub payroll_runs: Vec<PayrollRun>,
516 pub payroll_line_items: Vec<PayrollLineItem>,
518 pub time_entries: Vec<TimeEntry>,
520 pub expense_reports: Vec<ExpenseReport>,
522 pub payroll_run_count: usize,
524 pub payroll_line_item_count: usize,
526 pub time_entry_count: usize,
528 pub expense_report_count: usize,
530}
531
532#[derive(Debug, Clone, Default)]
534pub struct AccountingStandardsSnapshot {
535 pub contracts: Vec<datasynth_standards::accounting::revenue::CustomerContract>,
537 pub impairment_tests: Vec<datasynth_standards::accounting::impairment::ImpairmentTest>,
539 pub revenue_contract_count: usize,
541 pub impairment_test_count: usize,
543}
544
545#[derive(Debug, Clone, Default)]
547pub struct ManufacturingSnapshot {
548 pub production_orders: Vec<ProductionOrder>,
550 pub quality_inspections: Vec<QualityInspection>,
552 pub cycle_counts: Vec<CycleCount>,
554 pub production_order_count: usize,
556 pub quality_inspection_count: usize,
558 pub cycle_count_count: usize,
560}
561
562#[derive(Debug, Clone, Default)]
564pub struct SalesKpiBudgetsSnapshot {
565 pub sales_quotes: Vec<SalesQuote>,
567 pub kpis: Vec<ManagementKpi>,
569 pub budgets: Vec<Budget>,
571 pub sales_quote_count: usize,
573 pub kpi_count: usize,
575 pub budget_line_count: usize,
577}
578
579#[derive(Debug, Clone, Default)]
581pub struct AnomalyLabels {
582 pub labels: Vec<LabeledAnomaly>,
584 pub summary: Option<AnomalySummary>,
586 pub by_type: HashMap<String, usize>,
588}
589
590#[derive(Debug, Clone, Default)]
592pub struct BalanceValidationResult {
593 pub validated: bool,
595 pub is_balanced: bool,
597 pub entries_processed: u64,
599 pub total_debits: rust_decimal::Decimal,
601 pub total_credits: rust_decimal::Decimal,
603 pub accounts_tracked: usize,
605 pub companies_tracked: usize,
607 pub validation_errors: Vec<ValidationError>,
609 pub has_unbalanced_entries: bool,
611}
612
613#[derive(Debug, Clone, Default)]
615pub struct TaxSnapshot {
616 pub jurisdictions: Vec<TaxJurisdiction>,
618 pub codes: Vec<TaxCode>,
620 pub tax_lines: Vec<TaxLine>,
622 pub tax_returns: Vec<TaxReturn>,
624 pub tax_provisions: Vec<TaxProvision>,
626 pub withholding_records: Vec<WithholdingTaxRecord>,
628 pub tax_anomaly_labels: Vec<datasynth_generators::TaxAnomalyLabel>,
630 pub jurisdiction_count: usize,
632 pub code_count: usize,
634}
635
636#[derive(Debug, Clone, Default, Serialize, Deserialize)]
638pub struct IntercompanySnapshot {
639 pub matched_pairs: Vec<datasynth_core::models::intercompany::ICMatchedPair>,
641 pub seller_journal_entries: Vec<JournalEntry>,
643 pub buyer_journal_entries: Vec<JournalEntry>,
645 pub elimination_entries: Vec<datasynth_core::models::intercompany::EliminationEntry>,
647 pub matched_pair_count: usize,
649 pub elimination_entry_count: usize,
651 pub match_rate: f64,
653}
654
655#[derive(Debug, Clone, Default)]
657pub struct EsgSnapshot {
658 pub emissions: Vec<EmissionRecord>,
660 pub energy: Vec<EnergyConsumption>,
662 pub water: Vec<WaterUsage>,
664 pub waste: Vec<WasteRecord>,
666 pub diversity: Vec<WorkforceDiversityMetric>,
668 pub pay_equity: Vec<PayEquityMetric>,
670 pub safety_incidents: Vec<SafetyIncident>,
672 pub safety_metrics: Vec<SafetyMetric>,
674 pub governance: Vec<GovernanceMetric>,
676 pub supplier_assessments: Vec<SupplierEsgAssessment>,
678 pub materiality: Vec<MaterialityAssessment>,
680 pub disclosures: Vec<EsgDisclosure>,
682 pub climate_scenarios: Vec<ClimateScenario>,
684 pub anomaly_labels: Vec<EsgAnomalyLabel>,
686 pub emission_count: usize,
688 pub disclosure_count: usize,
690}
691
692#[derive(Debug, Clone, Default)]
694pub struct TreasurySnapshot {
695 pub cash_positions: Vec<CashPosition>,
697 pub cash_forecasts: Vec<CashForecast>,
699 pub cash_pools: Vec<CashPool>,
701 pub cash_pool_sweeps: Vec<CashPoolSweep>,
703 pub hedging_instruments: Vec<HedgingInstrument>,
705 pub hedge_relationships: Vec<HedgeRelationship>,
707 pub debt_instruments: Vec<DebtInstrument>,
709 pub treasury_anomaly_labels: Vec<datasynth_generators::treasury::TreasuryAnomalyLabel>,
711}
712
713#[derive(Debug, Clone, Default)]
715pub struct ProjectAccountingSnapshot {
716 pub projects: Vec<Project>,
718 pub cost_lines: Vec<ProjectCostLine>,
720 pub revenue_records: Vec<ProjectRevenue>,
722 pub earned_value_metrics: Vec<EarnedValueMetric>,
724 pub change_orders: Vec<ChangeOrder>,
726 pub milestones: Vec<ProjectMilestone>,
728}
729
730#[derive(Debug)]
732pub struct EnhancedGenerationResult {
733 pub chart_of_accounts: ChartOfAccounts,
735 pub master_data: MasterDataSnapshot,
737 pub document_flows: DocumentFlowSnapshot,
739 pub subledger: SubledgerSnapshot,
741 pub ocpm: OcpmSnapshot,
743 pub audit: AuditSnapshot,
745 pub banking: BankingSnapshot,
747 pub graph_export: GraphExportSnapshot,
749 pub sourcing: SourcingSnapshot,
751 pub financial_reporting: FinancialReportingSnapshot,
753 pub hr: HrSnapshot,
755 pub accounting_standards: AccountingStandardsSnapshot,
757 pub manufacturing: ManufacturingSnapshot,
759 pub sales_kpi_budgets: SalesKpiBudgetsSnapshot,
761 pub tax: TaxSnapshot,
763 pub esg: EsgSnapshot,
765 pub treasury: TreasurySnapshot,
767 pub project_accounting: ProjectAccountingSnapshot,
769 pub intercompany: IntercompanySnapshot,
771 pub journal_entries: Vec<JournalEntry>,
773 pub anomaly_labels: AnomalyLabels,
775 pub balance_validation: BalanceValidationResult,
777 pub data_quality_stats: DataQualityStats,
779 pub statistics: EnhancedGenerationStatistics,
781 pub lineage: Option<super::lineage::LineageGraph>,
783 pub gate_result: Option<datasynth_eval::gates::GateResult>,
785 pub internal_controls: Vec<InternalControl>,
787 pub opening_balances: Vec<GeneratedOpeningBalance>,
789 pub subledger_reconciliation: Vec<datasynth_generators::ReconciliationResult>,
791}
792
793#[derive(Debug, Clone, Default, Serialize, Deserialize)]
795pub struct EnhancedGenerationStatistics {
796 pub total_entries: u64,
798 pub total_line_items: u64,
800 pub accounts_count: usize,
802 pub companies_count: usize,
804 pub period_months: u32,
806 pub vendor_count: usize,
808 pub customer_count: usize,
809 pub material_count: usize,
810 pub asset_count: usize,
811 pub employee_count: usize,
812 pub p2p_chain_count: usize,
814 pub o2c_chain_count: usize,
815 pub ap_invoice_count: usize,
817 pub ar_invoice_count: usize,
818 pub ocpm_event_count: usize,
820 pub ocpm_object_count: usize,
821 pub ocpm_case_count: usize,
822 pub audit_engagement_count: usize,
824 pub audit_workpaper_count: usize,
825 pub audit_evidence_count: usize,
826 pub audit_risk_count: usize,
827 pub audit_finding_count: usize,
828 pub audit_judgment_count: usize,
829 pub anomalies_injected: usize,
831 pub data_quality_issues: usize,
833 pub banking_customer_count: usize,
835 pub banking_account_count: usize,
836 pub banking_transaction_count: usize,
837 pub banking_suspicious_count: usize,
838 pub graph_export_count: usize,
840 pub graph_node_count: usize,
841 pub graph_edge_count: usize,
842 #[serde(default)]
844 pub llm_enrichment_ms: u64,
845 #[serde(default)]
847 pub llm_vendors_enriched: usize,
848 #[serde(default)]
850 pub diffusion_enhancement_ms: u64,
851 #[serde(default)]
853 pub diffusion_samples_generated: usize,
854 #[serde(default)]
856 pub causal_generation_ms: u64,
857 #[serde(default)]
859 pub causal_samples_generated: usize,
860 #[serde(default)]
862 pub causal_validation_passed: Option<bool>,
863 #[serde(default)]
865 pub sourcing_project_count: usize,
866 #[serde(default)]
867 pub rfx_event_count: usize,
868 #[serde(default)]
869 pub bid_count: usize,
870 #[serde(default)]
871 pub contract_count: usize,
872 #[serde(default)]
873 pub catalog_item_count: usize,
874 #[serde(default)]
875 pub scorecard_count: usize,
876 #[serde(default)]
878 pub financial_statement_count: usize,
879 #[serde(default)]
880 pub bank_reconciliation_count: usize,
881 #[serde(default)]
883 pub payroll_run_count: usize,
884 #[serde(default)]
885 pub time_entry_count: usize,
886 #[serde(default)]
887 pub expense_report_count: usize,
888 #[serde(default)]
890 pub revenue_contract_count: usize,
891 #[serde(default)]
892 pub impairment_test_count: usize,
893 #[serde(default)]
895 pub production_order_count: usize,
896 #[serde(default)]
897 pub quality_inspection_count: usize,
898 #[serde(default)]
899 pub cycle_count_count: usize,
900 #[serde(default)]
902 pub sales_quote_count: usize,
903 #[serde(default)]
904 pub kpi_count: usize,
905 #[serde(default)]
906 pub budget_line_count: usize,
907 #[serde(default)]
909 pub tax_jurisdiction_count: usize,
910 #[serde(default)]
911 pub tax_code_count: usize,
912 #[serde(default)]
914 pub esg_emission_count: usize,
915 #[serde(default)]
916 pub esg_disclosure_count: usize,
917 #[serde(default)]
919 pub ic_matched_pair_count: usize,
920 #[serde(default)]
921 pub ic_elimination_count: usize,
922 #[serde(default)]
924 pub ic_transaction_count: usize,
925 #[serde(default)]
927 pub fa_subledger_count: usize,
928 #[serde(default)]
930 pub inventory_subledger_count: usize,
931 #[serde(default)]
933 pub treasury_debt_instrument_count: usize,
934 #[serde(default)]
936 pub treasury_hedging_instrument_count: usize,
937 #[serde(default)]
939 pub project_count: usize,
940 #[serde(default)]
942 pub project_change_order_count: usize,
943 #[serde(default)]
945 pub tax_provision_count: usize,
946 #[serde(default)]
948 pub opening_balance_count: usize,
949 #[serde(default)]
951 pub subledger_reconciliation_count: usize,
952 #[serde(default)]
954 pub tax_line_count: usize,
955 #[serde(default)]
957 pub project_cost_line_count: usize,
958 #[serde(default)]
960 pub cash_position_count: usize,
961}
962
963pub struct EnhancedOrchestrator {
965 config: GeneratorConfig,
966 phase_config: PhaseConfig,
967 coa: Option<Arc<ChartOfAccounts>>,
968 master_data: MasterDataSnapshot,
969 seed: u64,
970 multi_progress: Option<MultiProgress>,
971 resource_guard: ResourceGuard,
973 output_path: Option<PathBuf>,
975 copula_generators: Vec<CopulaGeneratorSpec>,
977 country_pack_registry: datasynth_core::CountryPackRegistry,
979}
980
981impl EnhancedOrchestrator {
982 pub fn new(config: GeneratorConfig, phase_config: PhaseConfig) -> SynthResult<Self> {
984 datasynth_config::validate_config(&config)?;
985
986 let seed = config.global.seed.unwrap_or_else(rand::random);
987
988 let resource_guard = Self::build_resource_guard(&config, None);
990
991 let country_pack_registry = match &config.country_packs {
993 Some(cp) => {
994 datasynth_core::CountryPackRegistry::new(cp.external_dir.as_deref(), &cp.overrides)
995 .map_err(|e| SynthError::config(e.to_string()))?
996 }
997 None => datasynth_core::CountryPackRegistry::builtin_only()
998 .map_err(|e| SynthError::config(e.to_string()))?,
999 };
1000
1001 Ok(Self {
1002 config,
1003 phase_config,
1004 coa: None,
1005 master_data: MasterDataSnapshot::default(),
1006 seed,
1007 multi_progress: None,
1008 resource_guard,
1009 output_path: None,
1010 copula_generators: Vec::new(),
1011 country_pack_registry,
1012 })
1013 }
1014
1015 pub fn with_defaults(config: GeneratorConfig) -> SynthResult<Self> {
1017 Self::new(config, PhaseConfig::default())
1018 }
1019
1020 pub fn with_progress(mut self, show: bool) -> Self {
1022 self.phase_config.show_progress = show;
1023 if show {
1024 self.multi_progress = Some(MultiProgress::new());
1025 }
1026 self
1027 }
1028
1029 pub fn with_output_path<P: Into<PathBuf>>(mut self, path: P) -> Self {
1031 let path = path.into();
1032 self.output_path = Some(path.clone());
1033 self.resource_guard = Self::build_resource_guard(&self.config, Some(path));
1035 self
1036 }
1037
1038 pub fn country_pack_registry(&self) -> &datasynth_core::CountryPackRegistry {
1040 &self.country_pack_registry
1041 }
1042
1043 pub fn country_pack_for(&self, country: &str) -> &datasynth_core::CountryPack {
1045 self.country_pack_registry.get_by_str(country)
1046 }
1047
1048 fn primary_country_code(&self) -> &str {
1051 self.config
1052 .companies
1053 .first()
1054 .map(|c| c.country.as_str())
1055 .unwrap_or("US")
1056 }
1057
1058 fn primary_pack(&self) -> &datasynth_core::CountryPack {
1060 self.country_pack_for(self.primary_country_code())
1061 }
1062
1063 pub fn has_copulas(&self) -> bool {
1068 !self.copula_generators.is_empty()
1069 }
1070
1071 pub fn copulas(&self) -> &[CopulaGeneratorSpec] {
1077 &self.copula_generators
1078 }
1079
1080 pub fn copulas_mut(&mut self) -> &mut [CopulaGeneratorSpec] {
1084 &mut self.copula_generators
1085 }
1086
1087 pub fn sample_from_copula(&mut self, copula_name: &str) -> Option<Vec<f64>> {
1091 self.copula_generators
1092 .iter_mut()
1093 .find(|c| c.name == copula_name)
1094 .map(|c| c.generator.sample())
1095 }
1096
1097 pub fn from_fingerprint(
1120 fingerprint_path: &std::path::Path,
1121 phase_config: PhaseConfig,
1122 scale: f64,
1123 ) -> SynthResult<Self> {
1124 info!("Loading fingerprint from: {}", fingerprint_path.display());
1125
1126 let reader = FingerprintReader::new();
1128 let fingerprint = reader
1129 .read_from_file(fingerprint_path)
1130 .map_err(|e| SynthError::config(format!("Failed to read fingerprint: {}", e)))?;
1131
1132 Self::from_fingerprint_data(fingerprint, phase_config, scale)
1133 }
1134
1135 pub fn from_fingerprint_data(
1142 fingerprint: Fingerprint,
1143 phase_config: PhaseConfig,
1144 scale: f64,
1145 ) -> SynthResult<Self> {
1146 info!(
1147 "Synthesizing config from fingerprint (version: {}, tables: {})",
1148 fingerprint.manifest.version,
1149 fingerprint.schema.tables.len()
1150 );
1151
1152 let seed: u64 = rand::random();
1154
1155 let options = SynthesisOptions {
1157 scale,
1158 seed: Some(seed),
1159 preserve_correlations: true,
1160 inject_anomalies: true,
1161 };
1162 let synthesizer = ConfigSynthesizer::with_options(options);
1163
1164 let synthesis_result = synthesizer
1166 .synthesize_full(&fingerprint, seed)
1167 .map_err(|e| {
1168 SynthError::config(format!(
1169 "Failed to synthesize config from fingerprint: {}",
1170 e
1171 ))
1172 })?;
1173
1174 let mut config = if let Some(ref industry) = fingerprint.manifest.source.industry {
1176 Self::base_config_for_industry(industry)
1177 } else {
1178 Self::base_config_for_industry("manufacturing")
1179 };
1180
1181 config = Self::apply_config_patch(config, &synthesis_result.config_patch);
1183
1184 info!(
1186 "Config synthesized: {} tables, scale={:.2}, copula generators: {}",
1187 fingerprint.schema.tables.len(),
1188 scale,
1189 synthesis_result.copula_generators.len()
1190 );
1191
1192 if !synthesis_result.copula_generators.is_empty() {
1193 for spec in &synthesis_result.copula_generators {
1194 info!(
1195 " Copula '{}' for table '{}': {} columns",
1196 spec.name,
1197 spec.table,
1198 spec.columns.len()
1199 );
1200 }
1201 }
1202
1203 let mut orchestrator = Self::new(config, phase_config)?;
1205
1206 orchestrator.copula_generators = synthesis_result.copula_generators;
1208
1209 Ok(orchestrator)
1210 }
1211
1212 fn base_config_for_industry(industry: &str) -> GeneratorConfig {
1214 use datasynth_config::presets::create_preset;
1215 use datasynth_config::TransactionVolume;
1216 use datasynth_core::models::{CoAComplexity, IndustrySector};
1217
1218 let sector = match industry.to_lowercase().as_str() {
1219 "manufacturing" => IndustrySector::Manufacturing,
1220 "retail" => IndustrySector::Retail,
1221 "financial" | "financial_services" => IndustrySector::FinancialServices,
1222 "healthcare" => IndustrySector::Healthcare,
1223 "technology" | "tech" => IndustrySector::Technology,
1224 _ => IndustrySector::Manufacturing,
1225 };
1226
1227 create_preset(
1229 sector,
1230 1, 12, CoAComplexity::Medium,
1233 TransactionVolume::TenK,
1234 )
1235 }
1236
1237 fn apply_config_patch(
1239 mut config: GeneratorConfig,
1240 patch: &datasynth_fingerprint::synthesis::ConfigPatch,
1241 ) -> GeneratorConfig {
1242 use datasynth_fingerprint::synthesis::ConfigValue;
1243
1244 for (key, value) in patch.values() {
1245 match (key.as_str(), value) {
1246 ("transactions.count", ConfigValue::Integer(n)) => {
1249 info!(
1250 "Fingerprint suggests {} transactions (apply via company volumes)",
1251 n
1252 );
1253 }
1254 ("global.period_months", ConfigValue::Integer(n)) => {
1255 config.global.period_months = *n as u32;
1256 }
1257 ("global.start_date", ConfigValue::String(s)) => {
1258 config.global.start_date = s.clone();
1259 }
1260 ("global.seed", ConfigValue::Integer(n)) => {
1261 config.global.seed = Some(*n as u64);
1262 }
1263 ("fraud.enabled", ConfigValue::Bool(b)) => {
1264 config.fraud.enabled = *b;
1265 }
1266 ("fraud.fraud_rate", ConfigValue::Float(f)) => {
1267 config.fraud.fraud_rate = *f;
1268 }
1269 ("data_quality.enabled", ConfigValue::Bool(b)) => {
1270 config.data_quality.enabled = *b;
1271 }
1272 ("anomaly_injection.enabled", ConfigValue::Bool(b)) => {
1274 config.fraud.enabled = *b;
1275 }
1276 ("anomaly_injection.overall_rate", ConfigValue::Float(f)) => {
1277 config.fraud.fraud_rate = *f;
1278 }
1279 _ => {
1280 debug!("Ignoring unknown config patch key: {}", key);
1281 }
1282 }
1283 }
1284
1285 config
1286 }
1287
1288 fn build_resource_guard(
1290 config: &GeneratorConfig,
1291 output_path: Option<PathBuf>,
1292 ) -> ResourceGuard {
1293 let mut builder = ResourceGuardBuilder::new();
1294
1295 if config.global.memory_limit_mb > 0 {
1297 builder = builder.memory_limit(config.global.memory_limit_mb);
1298 }
1299
1300 if let Some(path) = output_path {
1302 builder = builder.output_path(path).min_free_disk(100); }
1304
1305 builder = builder.conservative();
1307
1308 builder.build()
1309 }
1310
1311 fn check_resources(&self) -> SynthResult<DegradationLevel> {
1316 self.resource_guard.check()
1317 }
1318
1319 fn check_resources_with_log(&self, phase: &str) -> SynthResult<DegradationLevel> {
1321 let level = self.resource_guard.check()?;
1322
1323 if level != DegradationLevel::Normal {
1324 warn!(
1325 "Resource degradation at {}: level={}, memory={}MB, disk={}MB",
1326 phase,
1327 level,
1328 self.resource_guard.current_memory_mb(),
1329 self.resource_guard.available_disk_mb()
1330 );
1331 }
1332
1333 Ok(level)
1334 }
1335
1336 fn get_degradation_actions(&self) -> DegradationActions {
1338 self.resource_guard.get_actions()
1339 }
1340
1341 fn check_memory_limit(&self) -> SynthResult<()> {
1343 self.check_resources()?;
1344 Ok(())
1345 }
1346
1347 pub fn generate(&mut self) -> SynthResult<EnhancedGenerationResult> {
1349 info!("Starting enhanced generation workflow");
1350 info!(
1351 "Config: industry={:?}, period_months={}, companies={}",
1352 self.config.global.industry,
1353 self.config.global.period_months,
1354 self.config.companies.len()
1355 );
1356
1357 let initial_level = self.check_resources_with_log("initial")?;
1359 if initial_level == DegradationLevel::Emergency {
1360 return Err(SynthError::resource(
1361 "Insufficient resources to start generation",
1362 ));
1363 }
1364
1365 let mut stats = EnhancedGenerationStatistics {
1366 companies_count: self.config.companies.len(),
1367 period_months: self.config.global.period_months,
1368 ..Default::default()
1369 };
1370
1371 let coa = self.phase_chart_of_accounts(&mut stats)?;
1373
1374 self.phase_master_data(&mut stats)?;
1376
1377 let (mut document_flows, subledger, fa_journal_entries) =
1379 self.phase_document_flows(&mut stats)?;
1380
1381 let opening_balances = self.phase_opening_balances(&coa, &mut stats)?;
1383
1384 let mut entries = self.phase_journal_entries(&coa, &document_flows, &mut stats)?;
1392
1393 if !fa_journal_entries.is_empty() {
1395 debug!(
1396 "Appending {} FA acquisition JEs to main entries",
1397 fa_journal_entries.len()
1398 );
1399 entries.extend(fa_journal_entries);
1400 }
1401
1402 let actions = self.get_degradation_actions();
1404
1405 let sourcing = self.phase_sourcing_data(&mut stats)?;
1407
1408 if !sourcing.contracts.is_empty() {
1410 let mut linked_count = 0usize;
1411 for chain in &mut document_flows.p2p_chains {
1412 if chain.purchase_order.contract_id.is_none() {
1413 if let Some(contract) = sourcing
1414 .contracts
1415 .iter()
1416 .find(|c| c.vendor_id == chain.purchase_order.vendor_id)
1417 {
1418 chain.purchase_order.contract_id = Some(contract.contract_id.clone());
1419 linked_count += 1;
1420 }
1421 }
1422 }
1423 if linked_count > 0 {
1424 debug!(
1425 "Linked {} purchase orders to S2C contracts by vendor match",
1426 linked_count
1427 );
1428 }
1429 }
1430
1431 let intercompany = self.phase_intercompany(&mut stats)?;
1433
1434 if !intercompany.seller_journal_entries.is_empty()
1436 || !intercompany.buyer_journal_entries.is_empty()
1437 {
1438 let ic_je_count = intercompany.seller_journal_entries.len()
1439 + intercompany.buyer_journal_entries.len();
1440 entries.extend(intercompany.seller_journal_entries.iter().cloned());
1441 entries.extend(intercompany.buyer_journal_entries.iter().cloned());
1442 debug!(
1443 "Appended {} IC journal entries to main entries",
1444 ic_je_count
1445 );
1446 }
1447
1448 let hr = self.phase_hr_data(&mut stats)?;
1450
1451 if !hr.payroll_runs.is_empty() {
1453 let payroll_jes = Self::generate_payroll_jes(&hr.payroll_runs);
1454 debug!("Generated {} JEs from payroll runs", payroll_jes.len());
1455 entries.extend(payroll_jes);
1456 }
1457
1458 let manufacturing_snap = self.phase_manufacturing(&mut stats)?;
1460
1461 if !manufacturing_snap.production_orders.is_empty() {
1463 let mfg_jes = Self::generate_manufacturing_jes(&manufacturing_snap.production_orders);
1464 debug!("Generated {} JEs from production orders", mfg_jes.len());
1465 entries.extend(mfg_jes);
1466 }
1467
1468 if !entries.is_empty() {
1471 stats.total_entries = entries.len() as u64;
1472 stats.total_line_items = entries.iter().map(|e| e.line_count() as u64).sum();
1473 debug!(
1474 "Final entry count: {}, line items: {} (after all JE-generating phases)",
1475 stats.total_entries, stats.total_line_items
1476 );
1477 }
1478
1479 let anomaly_labels = self.phase_anomaly_injection(&mut entries, &actions, &mut stats)?;
1481
1482 let balance_validation = self.phase_balance_validation(&entries)?;
1484
1485 let subledger_reconciliation =
1487 self.phase_subledger_reconciliation(&subledger, &entries, &mut stats)?;
1488
1489 let data_quality_stats =
1491 self.phase_data_quality_injection(&mut entries, &actions, &mut stats)?;
1492
1493 let audit = self.phase_audit_data(&entries, &mut stats)?;
1495
1496 let banking = self.phase_banking_data(&mut stats)?;
1498
1499 let graph_export = self.phase_graph_export(&entries, &coa, &mut stats)?;
1501
1502 self.phase_llm_enrichment(&mut stats);
1504
1505 self.phase_diffusion_enhancement(&mut stats);
1507
1508 self.phase_causal_overlay(&mut stats);
1510
1511 let financial_reporting =
1513 self.phase_financial_reporting(&document_flows, &entries, &coa, &mut stats)?;
1514
1515 let accounting_standards = self.phase_accounting_standards(&mut stats)?;
1517
1518 let ocpm = self.phase_ocpm_events(
1520 &document_flows,
1521 &sourcing,
1522 &hr,
1523 &manufacturing_snap,
1524 &banking,
1525 &audit,
1526 &financial_reporting,
1527 &mut stats,
1528 )?;
1529
1530 let sales_kpi_budgets =
1532 self.phase_sales_kpi_budgets(&coa, &financial_reporting, &mut stats)?;
1533
1534 let tax = self.phase_tax_generation(&document_flows, &mut stats)?;
1536
1537 let esg_snap = self.phase_esg_generation(&document_flows, &mut stats)?;
1539
1540 let treasury = self.phase_treasury_data(&document_flows, &mut stats)?;
1542
1543 let project_accounting = self.phase_project_accounting(&document_flows, &hr, &mut stats)?;
1545
1546 self.phase_hypergraph_export(
1548 &coa,
1549 &entries,
1550 &document_flows,
1551 &sourcing,
1552 &hr,
1553 &manufacturing_snap,
1554 &banking,
1555 &audit,
1556 &financial_reporting,
1557 &ocpm,
1558 &mut stats,
1559 )?;
1560
1561 if self.phase_config.generate_graph_export || self.config.graph_export.enabled {
1564 self.build_additional_graphs(&banking, &intercompany, &entries, &mut stats);
1565 }
1566
1567 if self.config.streaming.enabled {
1569 info!("Note: streaming config is enabled but batch mode does not use it");
1570 }
1571 if self.config.vendor_network.enabled {
1572 debug!("Vendor network config available; relationship graph generation is partial");
1573 }
1574 if self.config.customer_segmentation.enabled {
1575 debug!("Customer segmentation config available; segment-aware generation is partial");
1576 }
1577
1578 let resource_stats = self.resource_guard.stats();
1580 info!(
1581 "Generation workflow complete. Resource stats: memory_peak={}MB, disk_written={}bytes, degradation_level={}",
1582 resource_stats.memory.peak_resident_bytes / (1024 * 1024),
1583 resource_stats.disk.estimated_bytes_written,
1584 resource_stats.degradation_level
1585 );
1586
1587 let lineage = self.build_lineage_graph();
1589
1590 let gate_result = if self.config.quality_gates.enabled {
1592 let profile_name = &self.config.quality_gates.profile;
1593 match datasynth_eval::gates::get_profile(profile_name) {
1594 Some(profile) => {
1595 let mut eval = datasynth_eval::ComprehensiveEvaluation::new();
1597
1598 if balance_validation.validated {
1600 eval.coherence.balance =
1601 Some(datasynth_eval::coherence::BalanceSheetEvaluation {
1602 equation_balanced: balance_validation.is_balanced,
1603 max_imbalance: (balance_validation.total_debits
1604 - balance_validation.total_credits)
1605 .abs(),
1606 periods_evaluated: 1,
1607 periods_imbalanced: if balance_validation.is_balanced {
1608 0
1609 } else {
1610 1
1611 },
1612 period_results: Vec::new(),
1613 companies_evaluated: self.config.companies.len(),
1614 });
1615 }
1616
1617 eval.coherence.passes = balance_validation.is_balanced;
1619 if !balance_validation.is_balanced {
1620 eval.coherence
1621 .failures
1622 .push("Balance sheet equation not satisfied".to_string());
1623 }
1624
1625 eval.statistical.overall_score = if entries.len() > 10 { 0.9 } else { 0.5 };
1627 eval.statistical.passes = !entries.is_empty();
1628
1629 eval.quality.overall_score = 0.9; eval.quality.passes = true;
1632
1633 let result = datasynth_eval::gates::GateEngine::evaluate(&eval, &profile);
1634 info!(
1635 "Quality gates evaluated (profile '{}'): {}/{} passed — {}",
1636 profile_name, result.gates_passed, result.gates_total, result.summary
1637 );
1638 Some(result)
1639 }
1640 None => {
1641 warn!(
1642 "Quality gates enabled but profile '{}' not found; skipping gate evaluation",
1643 profile_name
1644 );
1645 None
1646 }
1647 }
1648 } else {
1649 None
1650 };
1651
1652 let internal_controls = if self.config.internal_controls.enabled {
1654 InternalControl::standard_controls()
1655 } else {
1656 Vec::new()
1657 };
1658
1659 Ok(EnhancedGenerationResult {
1660 chart_of_accounts: (*coa).clone(),
1661 master_data: self.master_data.clone(),
1662 document_flows,
1663 subledger,
1664 ocpm,
1665 audit,
1666 banking,
1667 graph_export,
1668 sourcing,
1669 financial_reporting,
1670 hr,
1671 accounting_standards,
1672 manufacturing: manufacturing_snap,
1673 sales_kpi_budgets,
1674 tax,
1675 esg: esg_snap,
1676 treasury,
1677 project_accounting,
1678 intercompany,
1679 journal_entries: entries,
1680 anomaly_labels,
1681 balance_validation,
1682 data_quality_stats,
1683 statistics: stats,
1684 lineage: Some(lineage),
1685 gate_result,
1686 internal_controls,
1687 opening_balances,
1688 subledger_reconciliation,
1689 })
1690 }
1691
1692 fn phase_chart_of_accounts(
1698 &mut self,
1699 stats: &mut EnhancedGenerationStatistics,
1700 ) -> SynthResult<Arc<ChartOfAccounts>> {
1701 info!("Phase 1: Generating Chart of Accounts");
1702 let coa = self.generate_coa()?;
1703 stats.accounts_count = coa.account_count();
1704 info!(
1705 "Chart of Accounts generated: {} accounts",
1706 stats.accounts_count
1707 );
1708 self.check_resources_with_log("post-coa")?;
1709 Ok(coa)
1710 }
1711
1712 fn phase_master_data(&mut self, stats: &mut EnhancedGenerationStatistics) -> SynthResult<()> {
1714 if self.phase_config.generate_master_data {
1715 info!("Phase 2: Generating Master Data");
1716 self.generate_master_data()?;
1717 stats.vendor_count = self.master_data.vendors.len();
1718 stats.customer_count = self.master_data.customers.len();
1719 stats.material_count = self.master_data.materials.len();
1720 stats.asset_count = self.master_data.assets.len();
1721 stats.employee_count = self.master_data.employees.len();
1722 info!(
1723 "Master data generated: {} vendors, {} customers, {} materials, {} assets, {} employees",
1724 stats.vendor_count, stats.customer_count, stats.material_count,
1725 stats.asset_count, stats.employee_count
1726 );
1727 self.check_resources_with_log("post-master-data")?;
1728 } else {
1729 debug!("Phase 2: Skipped (master data generation disabled)");
1730 }
1731 Ok(())
1732 }
1733
1734 fn phase_document_flows(
1736 &mut self,
1737 stats: &mut EnhancedGenerationStatistics,
1738 ) -> SynthResult<(DocumentFlowSnapshot, SubledgerSnapshot, Vec<JournalEntry>)> {
1739 let mut document_flows = DocumentFlowSnapshot::default();
1740 let mut subledger = SubledgerSnapshot::default();
1741
1742 if self.phase_config.generate_document_flows && !self.master_data.vendors.is_empty() {
1743 info!("Phase 3: Generating Document Flows");
1744 self.generate_document_flows(&mut document_flows)?;
1745 stats.p2p_chain_count = document_flows.p2p_chains.len();
1746 stats.o2c_chain_count = document_flows.o2c_chains.len();
1747 info!(
1748 "Document flows generated: {} P2P chains, {} O2C chains",
1749 stats.p2p_chain_count, stats.o2c_chain_count
1750 );
1751
1752 debug!("Phase 3b: Linking document flows to subledgers");
1754 subledger = self.link_document_flows_to_subledgers(&document_flows)?;
1755 stats.ap_invoice_count = subledger.ap_invoices.len();
1756 stats.ar_invoice_count = subledger.ar_invoices.len();
1757 debug!(
1758 "Subledgers linked: {} AP invoices, {} AR invoices",
1759 stats.ap_invoice_count, stats.ar_invoice_count
1760 );
1761
1762 self.check_resources_with_log("post-document-flows")?;
1763 } else {
1764 debug!("Phase 3: Skipped (document flow generation disabled or no master data)");
1765 }
1766
1767 let mut fa_journal_entries = Vec::new();
1769 if !self.master_data.assets.is_empty() {
1770 debug!("Generating FA subledger records");
1771 let company_code = self
1772 .config
1773 .companies
1774 .first()
1775 .map(|c| c.code.as_str())
1776 .unwrap_or("1000");
1777 let currency = self
1778 .config
1779 .companies
1780 .first()
1781 .map(|c| c.currency.as_str())
1782 .unwrap_or("USD");
1783
1784 let mut fa_gen = datasynth_generators::FAGenerator::new(
1785 datasynth_generators::FAGeneratorConfig::default(),
1786 rand_chacha::ChaCha8Rng::seed_from_u64(self.seed + 70),
1787 );
1788
1789 for asset in &self.master_data.assets {
1790 let (record, je) = fa_gen.generate_asset_acquisition(
1791 company_code,
1792 &format!("{:?}", asset.asset_class),
1793 &asset.description,
1794 asset.acquisition_date,
1795 currency,
1796 asset.cost_center.as_deref(),
1797 );
1798 subledger.fa_records.push(record);
1799 fa_journal_entries.push(je);
1800 }
1801
1802 stats.fa_subledger_count = subledger.fa_records.len();
1803 debug!(
1804 "FA subledger records generated: {} (with {} acquisition JEs)",
1805 stats.fa_subledger_count,
1806 fa_journal_entries.len()
1807 );
1808 }
1809
1810 if !self.master_data.materials.is_empty() {
1812 debug!("Generating Inventory subledger records");
1813 let first_company = self.config.companies.first();
1814 let company_code = first_company.map(|c| c.code.as_str()).unwrap_or("1000");
1815 let inv_currency = first_company
1816 .map(|c| c.currency.clone())
1817 .unwrap_or_else(|| "USD".to_string());
1818
1819 let mut inv_gen = datasynth_generators::InventoryGenerator::new_with_currency(
1820 datasynth_generators::InventoryGeneratorConfig::default(),
1821 rand_chacha::ChaCha8Rng::seed_from_u64(self.seed + 71),
1822 inv_currency.clone(),
1823 );
1824
1825 for (i, material) in self.master_data.materials.iter().enumerate() {
1826 let plant = format!("PLANT{:02}", (i % 3) + 1);
1827 let storage_loc = format!("SL-{:03}", (i % 10) + 1);
1828 let initial_qty = rust_decimal::Decimal::from(
1829 material
1830 .safety_stock
1831 .to_string()
1832 .parse::<i64>()
1833 .unwrap_or(100),
1834 );
1835
1836 let position = inv_gen.generate_position(
1837 company_code,
1838 &plant,
1839 &storage_loc,
1840 &material.material_id,
1841 &material.description,
1842 initial_qty,
1843 Some(material.standard_cost),
1844 &inv_currency,
1845 );
1846 subledger.inventory_positions.push(position);
1847 }
1848
1849 stats.inventory_subledger_count = subledger.inventory_positions.len();
1850 debug!(
1851 "Inventory subledger records generated: {}",
1852 stats.inventory_subledger_count
1853 );
1854 }
1855
1856 Ok((document_flows, subledger, fa_journal_entries))
1857 }
1858
1859 #[allow(clippy::too_many_arguments)]
1861 fn phase_ocpm_events(
1862 &mut self,
1863 document_flows: &DocumentFlowSnapshot,
1864 sourcing: &SourcingSnapshot,
1865 hr: &HrSnapshot,
1866 manufacturing: &ManufacturingSnapshot,
1867 banking: &BankingSnapshot,
1868 audit: &AuditSnapshot,
1869 financial_reporting: &FinancialReportingSnapshot,
1870 stats: &mut EnhancedGenerationStatistics,
1871 ) -> SynthResult<OcpmSnapshot> {
1872 if self.phase_config.generate_ocpm_events {
1873 info!("Phase 3c: Generating OCPM Events");
1874 let ocpm_snapshot = self.generate_ocpm_events(
1875 document_flows,
1876 sourcing,
1877 hr,
1878 manufacturing,
1879 banking,
1880 audit,
1881 financial_reporting,
1882 )?;
1883 stats.ocpm_event_count = ocpm_snapshot.event_count;
1884 stats.ocpm_object_count = ocpm_snapshot.object_count;
1885 stats.ocpm_case_count = ocpm_snapshot.case_count;
1886 info!(
1887 "OCPM events generated: {} events, {} objects, {} cases",
1888 stats.ocpm_event_count, stats.ocpm_object_count, stats.ocpm_case_count
1889 );
1890 self.check_resources_with_log("post-ocpm")?;
1891 Ok(ocpm_snapshot)
1892 } else {
1893 debug!("Phase 3c: Skipped (OCPM generation disabled or no document flows)");
1894 Ok(OcpmSnapshot::default())
1895 }
1896 }
1897
1898 fn phase_journal_entries(
1900 &mut self,
1901 coa: &Arc<ChartOfAccounts>,
1902 document_flows: &DocumentFlowSnapshot,
1903 _stats: &mut EnhancedGenerationStatistics,
1904 ) -> SynthResult<Vec<JournalEntry>> {
1905 let mut entries = Vec::new();
1906
1907 if self.phase_config.generate_document_flows && !document_flows.p2p_chains.is_empty() {
1909 debug!("Phase 4a: Generating JEs from document flows");
1910 let flow_entries = self.generate_jes_from_document_flows(document_flows)?;
1911 debug!("Generated {} JEs from document flows", flow_entries.len());
1912 entries.extend(flow_entries);
1913 }
1914
1915 if self.phase_config.generate_journal_entries {
1917 info!("Phase 4: Generating Journal Entries");
1918 let je_entries = self.generate_journal_entries(coa)?;
1919 info!("Generated {} standalone journal entries", je_entries.len());
1920 entries.extend(je_entries);
1921 } else {
1922 debug!("Phase 4: Skipped (journal entry generation disabled)");
1923 }
1924
1925 if !entries.is_empty() {
1926 self.check_resources_with_log("post-journal-entries")?;
1929 }
1930
1931 Ok(entries)
1932 }
1933
1934 fn phase_anomaly_injection(
1936 &mut self,
1937 entries: &mut [JournalEntry],
1938 actions: &DegradationActions,
1939 stats: &mut EnhancedGenerationStatistics,
1940 ) -> SynthResult<AnomalyLabels> {
1941 if self.phase_config.inject_anomalies
1942 && !entries.is_empty()
1943 && !actions.skip_anomaly_injection
1944 {
1945 info!("Phase 5: Injecting Anomalies");
1946 let result = self.inject_anomalies(entries)?;
1947 stats.anomalies_injected = result.labels.len();
1948 info!("Injected {} anomalies", stats.anomalies_injected);
1949 self.check_resources_with_log("post-anomaly-injection")?;
1950 Ok(result)
1951 } else if actions.skip_anomaly_injection {
1952 warn!("Phase 5: Skipped due to resource degradation");
1953 Ok(AnomalyLabels::default())
1954 } else {
1955 debug!("Phase 5: Skipped (anomaly injection disabled or no entries)");
1956 Ok(AnomalyLabels::default())
1957 }
1958 }
1959
1960 fn phase_balance_validation(
1962 &mut self,
1963 entries: &[JournalEntry],
1964 ) -> SynthResult<BalanceValidationResult> {
1965 if self.phase_config.validate_balances && !entries.is_empty() {
1966 debug!("Phase 6: Validating Balances");
1967 let balance_validation = self.validate_journal_entries(entries)?;
1968 if balance_validation.is_balanced {
1969 debug!("Balance validation passed");
1970 } else {
1971 warn!(
1972 "Balance validation found {} errors",
1973 balance_validation.validation_errors.len()
1974 );
1975 }
1976 Ok(balance_validation)
1977 } else {
1978 Ok(BalanceValidationResult::default())
1979 }
1980 }
1981
1982 fn phase_data_quality_injection(
1984 &mut self,
1985 entries: &mut [JournalEntry],
1986 actions: &DegradationActions,
1987 stats: &mut EnhancedGenerationStatistics,
1988 ) -> SynthResult<DataQualityStats> {
1989 if self.phase_config.inject_data_quality
1990 && !entries.is_empty()
1991 && !actions.skip_data_quality
1992 {
1993 info!("Phase 7: Injecting Data Quality Variations");
1994 let dq_stats = self.inject_data_quality(entries)?;
1995 stats.data_quality_issues = dq_stats.records_with_issues;
1996 info!("Injected {} data quality issues", stats.data_quality_issues);
1997 self.check_resources_with_log("post-data-quality")?;
1998 Ok(dq_stats)
1999 } else if actions.skip_data_quality {
2000 warn!("Phase 7: Skipped due to resource degradation");
2001 Ok(DataQualityStats::default())
2002 } else {
2003 debug!("Phase 7: Skipped (data quality injection disabled or no entries)");
2004 Ok(DataQualityStats::default())
2005 }
2006 }
2007
2008 fn phase_audit_data(
2010 &mut self,
2011 entries: &[JournalEntry],
2012 stats: &mut EnhancedGenerationStatistics,
2013 ) -> SynthResult<AuditSnapshot> {
2014 if self.phase_config.generate_audit {
2015 info!("Phase 8: Generating Audit Data");
2016 let audit_snapshot = self.generate_audit_data(entries)?;
2017 stats.audit_engagement_count = audit_snapshot.engagements.len();
2018 stats.audit_workpaper_count = audit_snapshot.workpapers.len();
2019 stats.audit_evidence_count = audit_snapshot.evidence.len();
2020 stats.audit_risk_count = audit_snapshot.risk_assessments.len();
2021 stats.audit_finding_count = audit_snapshot.findings.len();
2022 stats.audit_judgment_count = audit_snapshot.judgments.len();
2023 info!(
2024 "Audit data generated: {} engagements, {} workpapers, {} evidence, {} risks, {} findings, {} judgments",
2025 stats.audit_engagement_count, stats.audit_workpaper_count,
2026 stats.audit_evidence_count, stats.audit_risk_count,
2027 stats.audit_finding_count, stats.audit_judgment_count
2028 );
2029 self.check_resources_with_log("post-audit")?;
2030 Ok(audit_snapshot)
2031 } else {
2032 debug!("Phase 8: Skipped (audit generation disabled)");
2033 Ok(AuditSnapshot::default())
2034 }
2035 }
2036
2037 fn phase_banking_data(
2039 &mut self,
2040 stats: &mut EnhancedGenerationStatistics,
2041 ) -> SynthResult<BankingSnapshot> {
2042 if self.phase_config.generate_banking && self.config.banking.enabled {
2043 info!("Phase 9: Generating Banking KYC/AML Data");
2044 let banking_snapshot = self.generate_banking_data()?;
2045 stats.banking_customer_count = banking_snapshot.customers.len();
2046 stats.banking_account_count = banking_snapshot.accounts.len();
2047 stats.banking_transaction_count = banking_snapshot.transactions.len();
2048 stats.banking_suspicious_count = banking_snapshot.suspicious_count;
2049 info!(
2050 "Banking data generated: {} customers, {} accounts, {} transactions ({} suspicious)",
2051 stats.banking_customer_count, stats.banking_account_count,
2052 stats.banking_transaction_count, stats.banking_suspicious_count
2053 );
2054 self.check_resources_with_log("post-banking")?;
2055 Ok(banking_snapshot)
2056 } else {
2057 debug!("Phase 9: Skipped (banking generation disabled)");
2058 Ok(BankingSnapshot::default())
2059 }
2060 }
2061
2062 fn phase_graph_export(
2064 &mut self,
2065 entries: &[JournalEntry],
2066 coa: &Arc<ChartOfAccounts>,
2067 stats: &mut EnhancedGenerationStatistics,
2068 ) -> SynthResult<GraphExportSnapshot> {
2069 if (self.phase_config.generate_graph_export || self.config.graph_export.enabled)
2070 && !entries.is_empty()
2071 {
2072 info!("Phase 10: Exporting Accounting Network Graphs");
2073 match self.export_graphs(entries, coa, stats) {
2074 Ok(snapshot) => {
2075 info!(
2076 "Graph export complete: {} graphs ({} nodes, {} edges)",
2077 snapshot.graph_count, stats.graph_node_count, stats.graph_edge_count
2078 );
2079 Ok(snapshot)
2080 }
2081 Err(e) => {
2082 warn!("Phase 10: Graph export failed: {}", e);
2083 Ok(GraphExportSnapshot::default())
2084 }
2085 }
2086 } else {
2087 debug!("Phase 10: Skipped (graph export disabled or no entries)");
2088 Ok(GraphExportSnapshot::default())
2089 }
2090 }
2091
2092 #[allow(clippy::too_many_arguments)]
2094 fn phase_hypergraph_export(
2095 &self,
2096 coa: &Arc<ChartOfAccounts>,
2097 entries: &[JournalEntry],
2098 document_flows: &DocumentFlowSnapshot,
2099 sourcing: &SourcingSnapshot,
2100 hr: &HrSnapshot,
2101 manufacturing: &ManufacturingSnapshot,
2102 banking: &BankingSnapshot,
2103 audit: &AuditSnapshot,
2104 financial_reporting: &FinancialReportingSnapshot,
2105 ocpm: &OcpmSnapshot,
2106 stats: &mut EnhancedGenerationStatistics,
2107 ) -> SynthResult<()> {
2108 if self.config.graph_export.hypergraph.enabled && !entries.is_empty() {
2109 info!("Phase 19b: Exporting Multi-Layer Hypergraph");
2110 match self.export_hypergraph(
2111 coa,
2112 entries,
2113 document_flows,
2114 sourcing,
2115 hr,
2116 manufacturing,
2117 banking,
2118 audit,
2119 financial_reporting,
2120 ocpm,
2121 stats,
2122 ) {
2123 Ok(info) => {
2124 info!(
2125 "Hypergraph export complete: {} nodes, {} edges, {} hyperedges",
2126 info.node_count, info.edge_count, info.hyperedge_count
2127 );
2128 }
2129 Err(e) => {
2130 warn!("Phase 10b: Hypergraph export failed: {}", e);
2131 }
2132 }
2133 } else {
2134 debug!("Phase 10b: Skipped (hypergraph export disabled or no entries)");
2135 }
2136 Ok(())
2137 }
2138
2139 fn phase_llm_enrichment(&mut self, stats: &mut EnhancedGenerationStatistics) {
2145 if !self.config.llm.enabled {
2146 debug!("Phase 11: Skipped (LLM enrichment disabled)");
2147 return;
2148 }
2149
2150 info!("Phase 11: Starting LLM Enrichment");
2151 let start = std::time::Instant::now();
2152
2153 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2154 let provider = Arc::new(MockLlmProvider::new(self.seed));
2155 let enricher = VendorLlmEnricher::new(provider);
2156
2157 let industry = format!("{:?}", self.config.global.industry);
2158 let max_enrichments = self
2159 .config
2160 .llm
2161 .max_vendor_enrichments
2162 .min(self.master_data.vendors.len());
2163
2164 let mut enriched_count = 0usize;
2165 for vendor in self.master_data.vendors.iter_mut().take(max_enrichments) {
2166 match enricher.enrich_vendor_name(&industry, "general", &vendor.country) {
2167 Ok(name) => {
2168 vendor.name = name;
2169 enriched_count += 1;
2170 }
2171 Err(e) => {
2172 warn!(
2173 "LLM vendor enrichment failed for {}: {}",
2174 vendor.vendor_id, e
2175 );
2176 }
2177 }
2178 }
2179
2180 enriched_count
2181 }));
2182
2183 match result {
2184 Ok(enriched_count) => {
2185 stats.llm_vendors_enriched = enriched_count;
2186 let elapsed = start.elapsed();
2187 stats.llm_enrichment_ms = elapsed.as_millis() as u64;
2188 info!(
2189 "Phase 11 complete: {} vendors enriched in {}ms",
2190 enriched_count, stats.llm_enrichment_ms
2191 );
2192 }
2193 Err(_) => {
2194 let elapsed = start.elapsed();
2195 stats.llm_enrichment_ms = elapsed.as_millis() as u64;
2196 warn!("Phase 11: LLM enrichment failed (panic caught), continuing");
2197 }
2198 }
2199 }
2200
2201 fn phase_diffusion_enhancement(&self, stats: &mut EnhancedGenerationStatistics) {
2207 if !self.config.diffusion.enabled {
2208 debug!("Phase 12: Skipped (diffusion enhancement disabled)");
2209 return;
2210 }
2211
2212 info!("Phase 12: Starting Diffusion Enhancement");
2213 let start = std::time::Instant::now();
2214
2215 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2216 let means = vec![5000.0, 3.0, 2.0]; let stds = vec![2000.0, 1.5, 1.0];
2219
2220 let diffusion_config = DiffusionConfig {
2221 n_steps: self.config.diffusion.n_steps,
2222 seed: self.seed,
2223 ..Default::default()
2224 };
2225
2226 let backend = StatisticalDiffusionBackend::new(means, stds, diffusion_config);
2227
2228 let n_samples = self.config.diffusion.sample_size;
2229 let n_features = 3; let samples = backend.generate(n_samples, n_features, self.seed);
2231
2232 samples.len()
2233 }));
2234
2235 match result {
2236 Ok(sample_count) => {
2237 stats.diffusion_samples_generated = sample_count;
2238 let elapsed = start.elapsed();
2239 stats.diffusion_enhancement_ms = elapsed.as_millis() as u64;
2240 info!(
2241 "Phase 12 complete: {} diffusion samples generated in {}ms",
2242 sample_count, stats.diffusion_enhancement_ms
2243 );
2244 }
2245 Err(_) => {
2246 let elapsed = start.elapsed();
2247 stats.diffusion_enhancement_ms = elapsed.as_millis() as u64;
2248 warn!("Phase 12: Diffusion enhancement failed (panic caught), continuing");
2249 }
2250 }
2251 }
2252
2253 fn phase_causal_overlay(&self, stats: &mut EnhancedGenerationStatistics) {
2260 if !self.config.causal.enabled {
2261 debug!("Phase 13: Skipped (causal generation disabled)");
2262 return;
2263 }
2264
2265 info!("Phase 13: Starting Causal Overlay");
2266 let start = std::time::Instant::now();
2267
2268 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2269 let graph = match self.config.causal.template.as_str() {
2271 "revenue_cycle" => CausalGraph::revenue_cycle_template(),
2272 _ => CausalGraph::fraud_detection_template(),
2273 };
2274
2275 let scm = StructuralCausalModel::new(graph.clone())
2276 .map_err(|e| SynthError::generation(format!("Failed to build SCM: {}", e)))?;
2277
2278 let n_samples = self.config.causal.sample_size;
2279 let samples = scm
2280 .generate(n_samples, self.seed)
2281 .map_err(|e| SynthError::generation(format!("SCM generation failed: {}", e)))?;
2282
2283 let validation_passed = if self.config.causal.validate {
2285 let report = CausalValidator::validate_causal_structure(&samples, &graph);
2286 if report.valid {
2287 info!(
2288 "Causal validation passed: all {} checks OK",
2289 report.checks.len()
2290 );
2291 } else {
2292 warn!(
2293 "Causal validation: {} violations detected: {:?}",
2294 report.violations.len(),
2295 report.violations
2296 );
2297 }
2298 Some(report.valid)
2299 } else {
2300 None
2301 };
2302
2303 Ok::<(usize, Option<bool>), SynthError>((samples.len(), validation_passed))
2304 }));
2305
2306 match result {
2307 Ok(Ok((sample_count, validation_passed))) => {
2308 stats.causal_samples_generated = sample_count;
2309 stats.causal_validation_passed = validation_passed;
2310 let elapsed = start.elapsed();
2311 stats.causal_generation_ms = elapsed.as_millis() as u64;
2312 info!(
2313 "Phase 13 complete: {} causal samples generated in {}ms (validation: {:?})",
2314 sample_count, stats.causal_generation_ms, validation_passed,
2315 );
2316 }
2317 Ok(Err(e)) => {
2318 let elapsed = start.elapsed();
2319 stats.causal_generation_ms = elapsed.as_millis() as u64;
2320 warn!("Phase 13: Causal generation failed: {}", e);
2321 }
2322 Err(_) => {
2323 let elapsed = start.elapsed();
2324 stats.causal_generation_ms = elapsed.as_millis() as u64;
2325 warn!("Phase 13: Causal generation failed (panic caught), continuing");
2326 }
2327 }
2328 }
2329
2330 fn phase_sourcing_data(
2332 &mut self,
2333 stats: &mut EnhancedGenerationStatistics,
2334 ) -> SynthResult<SourcingSnapshot> {
2335 if !self.phase_config.generate_sourcing && !self.config.source_to_pay.enabled {
2336 debug!("Phase 14: Skipped (sourcing generation disabled)");
2337 return Ok(SourcingSnapshot::default());
2338 }
2339
2340 info!("Phase 14: Generating S2C Sourcing Data");
2341 let seed = self.seed;
2342
2343 let vendor_ids: Vec<String> = self
2345 .master_data
2346 .vendors
2347 .iter()
2348 .map(|v| v.vendor_id.clone())
2349 .collect();
2350 if vendor_ids.is_empty() {
2351 debug!("Phase 14: Skipped (no vendors available)");
2352 return Ok(SourcingSnapshot::default());
2353 }
2354
2355 let categories: Vec<(String, String)> = vec![
2356 ("CAT-RAW".to_string(), "Raw Materials".to_string()),
2357 ("CAT-OFF".to_string(), "Office Supplies".to_string()),
2358 ("CAT-IT".to_string(), "IT Equipment".to_string()),
2359 ("CAT-SVC".to_string(), "Professional Services".to_string()),
2360 ("CAT-LOG".to_string(), "Logistics".to_string()),
2361 ];
2362 let categories_with_spend: Vec<(String, String, rust_decimal::Decimal)> = categories
2363 .iter()
2364 .map(|(id, name)| {
2365 (
2366 id.clone(),
2367 name.clone(),
2368 rust_decimal::Decimal::from(100_000),
2369 )
2370 })
2371 .collect();
2372
2373 let company_code = self
2374 .config
2375 .companies
2376 .first()
2377 .map(|c| c.code.as_str())
2378 .unwrap_or("1000");
2379 let start_date = NaiveDate::parse_from_str(&self.config.global.start_date, "%Y-%m-%d")
2380 .map_err(|e| SynthError::config(format!("Invalid start_date: {}", e)))?;
2381 let end_date = start_date + chrono::Months::new(self.config.global.period_months);
2382 let fiscal_year = start_date.year() as u16;
2383 let owner_ids: Vec<String> = self
2384 .master_data
2385 .employees
2386 .iter()
2387 .take(5)
2388 .map(|e| e.employee_id.clone())
2389 .collect();
2390 let owner_id = owner_ids.first().map(|s| s.as_str()).unwrap_or("BUYER-001");
2391
2392 let mut spend_gen = SpendAnalysisGenerator::new(seed);
2394 let spend_analyses =
2395 spend_gen.generate(company_code, &vendor_ids, &categories, fiscal_year);
2396
2397 let mut project_gen = SourcingProjectGenerator::new(seed + 1);
2399 let sourcing_projects = if owner_ids.is_empty() {
2400 Vec::new()
2401 } else {
2402 project_gen.generate(
2403 company_code,
2404 &categories_with_spend,
2405 &owner_ids,
2406 start_date,
2407 self.config.global.period_months,
2408 )
2409 };
2410 stats.sourcing_project_count = sourcing_projects.len();
2411
2412 let qual_vendor_ids: Vec<String> = vendor_ids.iter().take(20).cloned().collect();
2414 let mut qual_gen = QualificationGenerator::new(seed + 2);
2415 let qualifications = qual_gen.generate(
2416 company_code,
2417 &qual_vendor_ids,
2418 sourcing_projects.first().map(|p| p.project_id.as_str()),
2419 owner_id,
2420 start_date,
2421 );
2422
2423 let mut rfx_gen = RfxGenerator::new(seed + 3);
2425 let rfx_events: Vec<RfxEvent> = sourcing_projects
2426 .iter()
2427 .map(|proj| {
2428 let qualified_vids: Vec<String> = vendor_ids.iter().take(5).cloned().collect();
2429 rfx_gen.generate(
2430 company_code,
2431 &proj.project_id,
2432 &proj.category_id,
2433 &qualified_vids,
2434 owner_id,
2435 start_date,
2436 50000.0,
2437 )
2438 })
2439 .collect();
2440 stats.rfx_event_count = rfx_events.len();
2441
2442 let mut bid_gen = BidGenerator::new(seed + 4);
2444 let mut all_bids = Vec::new();
2445 for rfx in &rfx_events {
2446 let bidder_count = vendor_ids.len().clamp(2, 5);
2447 let responding: Vec<String> = vendor_ids.iter().take(bidder_count).cloned().collect();
2448 let bids = bid_gen.generate(rfx, &responding, start_date);
2449 all_bids.extend(bids);
2450 }
2451 stats.bid_count = all_bids.len();
2452
2453 let mut eval_gen = BidEvaluationGenerator::new(seed + 5);
2455 let bid_evaluations: Vec<BidEvaluation> = rfx_events
2456 .iter()
2457 .map(|rfx| {
2458 let rfx_bids: Vec<SupplierBid> = all_bids
2459 .iter()
2460 .filter(|b| b.rfx_id == rfx.rfx_id)
2461 .cloned()
2462 .collect();
2463 eval_gen.evaluate(rfx, &rfx_bids, owner_id)
2464 })
2465 .collect();
2466
2467 let mut contract_gen = ContractGenerator::new(seed + 6);
2469 let contracts: Vec<ProcurementContract> = bid_evaluations
2470 .iter()
2471 .zip(rfx_events.iter())
2472 .filter_map(|(eval, rfx)| {
2473 eval.ranked_bids.first().and_then(|winner| {
2474 all_bids
2475 .iter()
2476 .find(|b| b.bid_id == winner.bid_id)
2477 .map(|winning_bid| {
2478 contract_gen.generate_from_bid(
2479 winning_bid,
2480 Some(&rfx.sourcing_project_id),
2481 &rfx.category_id,
2482 owner_id,
2483 start_date,
2484 )
2485 })
2486 })
2487 })
2488 .collect();
2489 stats.contract_count = contracts.len();
2490
2491 let mut catalog_gen = CatalogGenerator::new(seed + 7);
2493 let catalog_items = catalog_gen.generate(&contracts);
2494 stats.catalog_item_count = catalog_items.len();
2495
2496 let mut scorecard_gen = ScorecardGenerator::new(seed + 8);
2498 let vendor_contracts: Vec<(String, Vec<&ProcurementContract>)> = contracts
2499 .iter()
2500 .fold(
2501 std::collections::HashMap::<String, Vec<&ProcurementContract>>::new(),
2502 |mut acc, c| {
2503 acc.entry(c.vendor_id.clone()).or_default().push(c);
2504 acc
2505 },
2506 )
2507 .into_iter()
2508 .collect();
2509 let scorecards = scorecard_gen.generate(
2510 company_code,
2511 &vendor_contracts,
2512 start_date,
2513 end_date,
2514 owner_id,
2515 );
2516 stats.scorecard_count = scorecards.len();
2517
2518 let mut sourcing_projects = sourcing_projects;
2521 for project in &mut sourcing_projects {
2522 project.rfx_ids = rfx_events
2524 .iter()
2525 .filter(|rfx| rfx.sourcing_project_id == project.project_id)
2526 .map(|rfx| rfx.rfx_id.clone())
2527 .collect();
2528
2529 project.contract_id = contracts
2531 .iter()
2532 .find(|c| {
2533 c.sourcing_project_id
2534 .as_deref()
2535 .is_some_and(|sp| sp == project.project_id)
2536 })
2537 .map(|c| c.contract_id.clone());
2538
2539 project.spend_analysis_id = spend_analyses
2541 .iter()
2542 .find(|sa| sa.category_id == project.category_id)
2543 .map(|sa| sa.category_id.clone());
2544 }
2545
2546 info!(
2547 "S2C sourcing generated: {} projects, {} RFx, {} bids, {} contracts, {} catalog items, {} scorecards",
2548 stats.sourcing_project_count, stats.rfx_event_count, stats.bid_count,
2549 stats.contract_count, stats.catalog_item_count, stats.scorecard_count
2550 );
2551 self.check_resources_with_log("post-sourcing")?;
2552
2553 Ok(SourcingSnapshot {
2554 spend_analyses,
2555 sourcing_projects,
2556 qualifications,
2557 rfx_events,
2558 bids: all_bids,
2559 bid_evaluations,
2560 contracts,
2561 catalog_items,
2562 scorecards,
2563 })
2564 }
2565
2566 fn phase_intercompany(
2568 &mut self,
2569 stats: &mut EnhancedGenerationStatistics,
2570 ) -> SynthResult<IntercompanySnapshot> {
2571 if !self.phase_config.generate_intercompany && !self.config.intercompany.enabled {
2573 debug!("Phase 14b: Skipped (intercompany generation disabled)");
2574 return Ok(IntercompanySnapshot::default());
2575 }
2576
2577 if self.config.companies.len() < 2 {
2579 debug!(
2580 "Phase 14b: Skipped (intercompany requires 2+ companies, found {})",
2581 self.config.companies.len()
2582 );
2583 return Ok(IntercompanySnapshot::default());
2584 }
2585
2586 info!("Phase 14b: Generating Intercompany Transactions");
2587
2588 let seed = self.seed;
2589 let start_date = NaiveDate::parse_from_str(&self.config.global.start_date, "%Y-%m-%d")
2590 .map_err(|e| SynthError::config(format!("Invalid start_date: {}", e)))?;
2591 let end_date = start_date + chrono::Months::new(self.config.global.period_months);
2592
2593 let parent_code = self.config.companies[0].code.clone();
2596 let mut ownership_structure =
2597 datasynth_core::models::intercompany::OwnershipStructure::new(parent_code.clone());
2598
2599 for (i, company) in self.config.companies.iter().skip(1).enumerate() {
2600 let relationship = datasynth_core::models::intercompany::IntercompanyRelationship::new(
2601 format!("REL{:03}", i + 1),
2602 parent_code.clone(),
2603 company.code.clone(),
2604 rust_decimal::Decimal::from(100), start_date,
2606 );
2607 ownership_structure.add_relationship(relationship);
2608 }
2609
2610 let tp_method = match self.config.intercompany.transfer_pricing_method {
2612 datasynth_config::schema::TransferPricingMethod::CostPlus => {
2613 datasynth_core::models::intercompany::TransferPricingMethod::CostPlus
2614 }
2615 datasynth_config::schema::TransferPricingMethod::ComparableUncontrolled => {
2616 datasynth_core::models::intercompany::TransferPricingMethod::ComparableUncontrolled
2617 }
2618 datasynth_config::schema::TransferPricingMethod::ResalePrice => {
2619 datasynth_core::models::intercompany::TransferPricingMethod::ResalePrice
2620 }
2621 datasynth_config::schema::TransferPricingMethod::TransactionalNetMargin => {
2622 datasynth_core::models::intercompany::TransferPricingMethod::TransactionalNetMargin
2623 }
2624 datasynth_config::schema::TransferPricingMethod::ProfitSplit => {
2625 datasynth_core::models::intercompany::TransferPricingMethod::ProfitSplit
2626 }
2627 };
2628
2629 let ic_currency = self
2631 .config
2632 .companies
2633 .first()
2634 .map(|c| c.currency.clone())
2635 .unwrap_or_else(|| "USD".to_string());
2636 let ic_gen_config = datasynth_generators::ICGeneratorConfig {
2637 ic_transaction_rate: self.config.intercompany.ic_transaction_rate,
2638 transfer_pricing_method: tp_method,
2639 markup_percent: rust_decimal::Decimal::from_f64_retain(
2640 self.config.intercompany.markup_percent,
2641 )
2642 .unwrap_or(rust_decimal::Decimal::from(5)),
2643 generate_matched_pairs: self.config.intercompany.generate_matched_pairs,
2644 default_currency: ic_currency,
2645 ..Default::default()
2646 };
2647
2648 let mut ic_generator = datasynth_generators::ICGenerator::new(
2650 ic_gen_config,
2651 ownership_structure.clone(),
2652 seed + 50,
2653 );
2654
2655 let transactions_per_day = 3;
2658 let matched_pairs = ic_generator.generate_transactions_for_period(
2659 start_date,
2660 end_date,
2661 transactions_per_day,
2662 );
2663
2664 let mut seller_entries = Vec::new();
2666 let mut buyer_entries = Vec::new();
2667 let fiscal_year = start_date.year();
2668
2669 for pair in &matched_pairs {
2670 let fiscal_period = pair.posting_date.month();
2671 let (seller_je, buyer_je) =
2672 ic_generator.generate_journal_entries(pair, fiscal_year, fiscal_period);
2673 seller_entries.push(seller_je);
2674 buyer_entries.push(buyer_je);
2675 }
2676
2677 let matching_config = datasynth_generators::ICMatchingConfig {
2679 base_currency: self
2680 .config
2681 .companies
2682 .first()
2683 .map(|c| c.currency.clone())
2684 .unwrap_or_else(|| "USD".to_string()),
2685 ..Default::default()
2686 };
2687 let mut matching_engine = datasynth_generators::ICMatchingEngine::new(matching_config);
2688 matching_engine.load_matched_pairs(&matched_pairs);
2689 let matching_result = matching_engine.run_matching(end_date);
2690
2691 let mut elimination_entries = Vec::new();
2693 if self.config.intercompany.generate_eliminations {
2694 let elim_config = datasynth_generators::EliminationConfig {
2695 consolidation_entity: "GROUP".to_string(),
2696 base_currency: self
2697 .config
2698 .companies
2699 .first()
2700 .map(|c| c.currency.clone())
2701 .unwrap_or_else(|| "USD".to_string()),
2702 ..Default::default()
2703 };
2704
2705 let mut elim_generator =
2706 datasynth_generators::EliminationGenerator::new(elim_config, ownership_structure);
2707
2708 let fiscal_period = format!("{}{:02}", fiscal_year, end_date.month());
2709 let all_balances: Vec<datasynth_core::models::intercompany::ICAggregatedBalance> =
2710 matching_result
2711 .matched_balances
2712 .iter()
2713 .chain(matching_result.unmatched_balances.iter())
2714 .cloned()
2715 .collect();
2716
2717 let journal = elim_generator.generate_eliminations(
2718 &fiscal_period,
2719 end_date,
2720 &all_balances,
2721 &matched_pairs,
2722 &std::collections::HashMap::new(), &std::collections::HashMap::new(), );
2725
2726 elimination_entries = journal.entries.clone();
2727 }
2728
2729 let matched_pair_count = matched_pairs.len();
2730 let elimination_entry_count = elimination_entries.len();
2731 let match_rate = matching_result.match_rate;
2732
2733 stats.ic_matched_pair_count = matched_pair_count;
2734 stats.ic_elimination_count = elimination_entry_count;
2735 stats.ic_transaction_count = seller_entries.len() + buyer_entries.len();
2736
2737 info!(
2738 "Intercompany data generated: {} matched pairs, {} JEs ({} seller + {} buyer), {} elimination entries, {:.1}% match rate",
2739 matched_pair_count,
2740 stats.ic_transaction_count,
2741 seller_entries.len(),
2742 buyer_entries.len(),
2743 elimination_entry_count,
2744 match_rate * 100.0
2745 );
2746 self.check_resources_with_log("post-intercompany")?;
2747
2748 Ok(IntercompanySnapshot {
2749 matched_pairs,
2750 seller_journal_entries: seller_entries,
2751 buyer_journal_entries: buyer_entries,
2752 elimination_entries,
2753 matched_pair_count,
2754 elimination_entry_count,
2755 match_rate,
2756 })
2757 }
2758
2759 fn phase_financial_reporting(
2761 &mut self,
2762 document_flows: &DocumentFlowSnapshot,
2763 journal_entries: &[JournalEntry],
2764 coa: &Arc<ChartOfAccounts>,
2765 stats: &mut EnhancedGenerationStatistics,
2766 ) -> SynthResult<FinancialReportingSnapshot> {
2767 let fs_enabled = self.phase_config.generate_financial_statements
2768 || self.config.financial_reporting.enabled;
2769 let br_enabled = self.phase_config.generate_bank_reconciliation;
2770
2771 if !fs_enabled && !br_enabled {
2772 debug!("Phase 15: Skipped (financial reporting disabled)");
2773 return Ok(FinancialReportingSnapshot::default());
2774 }
2775
2776 info!("Phase 15: Generating Financial Reporting Data");
2777
2778 let seed = self.seed;
2779 let start_date = NaiveDate::parse_from_str(&self.config.global.start_date, "%Y-%m-%d")
2780 .map_err(|e| SynthError::config(format!("Invalid start_date: {}", e)))?;
2781
2782 let mut financial_statements = Vec::new();
2783 let mut bank_reconciliations = Vec::new();
2784 let mut trial_balances = Vec::new();
2785
2786 if fs_enabled {
2794 let company_code = self
2795 .config
2796 .companies
2797 .first()
2798 .map(|c| c.code.as_str())
2799 .unwrap_or("1000");
2800 let currency = self
2801 .config
2802 .companies
2803 .first()
2804 .map(|c| c.currency.as_str())
2805 .unwrap_or("USD");
2806 let has_journal_entries = !journal_entries.is_empty();
2807
2808 let mut fs_gen = FinancialStatementGenerator::new(seed + 20);
2811
2812 let mut prior_cumulative_tb: Option<Vec<datasynth_generators::TrialBalanceEntry>> =
2814 None;
2815
2816 for period in 0..self.config.global.period_months {
2818 let period_start = start_date + chrono::Months::new(period);
2819 let period_end =
2820 start_date + chrono::Months::new(period + 1) - chrono::Days::new(1);
2821 let fiscal_year = period_end.year() as u16;
2822 let fiscal_period = period_end.month() as u8;
2823
2824 if has_journal_entries {
2825 let tb_entries = Self::build_cumulative_trial_balance(
2828 journal_entries,
2829 coa,
2830 company_code,
2831 start_date,
2832 period_end,
2833 fiscal_year,
2834 fiscal_period,
2835 );
2836
2837 let prior_ref = prior_cumulative_tb.as_deref();
2840 let stmts = fs_gen.generate(
2841 company_code,
2842 currency,
2843 &tb_entries,
2844 period_start,
2845 period_end,
2846 fiscal_year,
2847 fiscal_period,
2848 prior_ref,
2849 "SYS-AUTOCLOSE",
2850 );
2851
2852 for stmt in stmts {
2854 if stmt.statement_type == StatementType::CashFlowStatement {
2855 let net_income = Self::calculate_net_income_from_tb(&tb_entries);
2857 let cf_items = Self::build_cash_flow_from_trial_balances(
2858 &tb_entries,
2859 prior_ref,
2860 net_income,
2861 );
2862 financial_statements.push(FinancialStatement {
2863 cash_flow_items: cf_items,
2864 ..stmt
2865 });
2866 } else {
2867 financial_statements.push(stmt);
2868 }
2869 }
2870
2871 trial_balances.push(PeriodTrialBalance {
2873 fiscal_year,
2874 fiscal_period,
2875 period_start,
2876 period_end,
2877 entries: tb_entries.clone(),
2878 });
2879
2880 prior_cumulative_tb = Some(tb_entries);
2882 } else {
2883 let tb_entries = Self::build_trial_balance_from_entries(
2886 journal_entries,
2887 coa,
2888 company_code,
2889 fiscal_year,
2890 fiscal_period,
2891 );
2892
2893 let stmts = fs_gen.generate(
2894 company_code,
2895 currency,
2896 &tb_entries,
2897 period_start,
2898 period_end,
2899 fiscal_year,
2900 fiscal_period,
2901 None,
2902 "SYS-AUTOCLOSE",
2903 );
2904 financial_statements.extend(stmts);
2905
2906 if !tb_entries.is_empty() {
2908 trial_balances.push(PeriodTrialBalance {
2909 fiscal_year,
2910 fiscal_period,
2911 period_start,
2912 period_end,
2913 entries: tb_entries,
2914 });
2915 }
2916 }
2917 }
2918 stats.financial_statement_count = financial_statements.len();
2919 info!(
2920 "Financial statements generated: {} statements (JE-derived: {})",
2921 stats.financial_statement_count, has_journal_entries
2922 );
2923 }
2924
2925 if br_enabled && !document_flows.payments.is_empty() {
2927 let employee_ids: Vec<String> = self
2928 .master_data
2929 .employees
2930 .iter()
2931 .map(|e| e.employee_id.clone())
2932 .collect();
2933 let mut br_gen =
2934 BankReconciliationGenerator::new(seed + 25).with_employee_pool(employee_ids);
2935
2936 for company in &self.config.companies {
2938 let company_payments: Vec<PaymentReference> = document_flows
2939 .payments
2940 .iter()
2941 .filter(|p| p.header.company_code == company.code)
2942 .map(|p| PaymentReference {
2943 id: p.header.document_id.clone(),
2944 amount: if p.is_vendor { p.amount } else { -p.amount },
2945 date: p.header.document_date,
2946 reference: p
2947 .check_number
2948 .clone()
2949 .or_else(|| p.wire_reference.clone())
2950 .unwrap_or_else(|| p.header.document_id.clone()),
2951 })
2952 .collect();
2953
2954 if company_payments.is_empty() {
2955 continue;
2956 }
2957
2958 let bank_account_id = format!("{}-MAIN", company.code);
2959
2960 for period in 0..self.config.global.period_months {
2962 let period_start = start_date + chrono::Months::new(period);
2963 let period_end =
2964 start_date + chrono::Months::new(period + 1) - chrono::Days::new(1);
2965
2966 let period_payments: Vec<PaymentReference> = company_payments
2967 .iter()
2968 .filter(|p| p.date >= period_start && p.date <= period_end)
2969 .cloned()
2970 .collect();
2971
2972 let recon = br_gen.generate(
2973 &company.code,
2974 &bank_account_id,
2975 period_start,
2976 period_end,
2977 &company.currency,
2978 &period_payments,
2979 );
2980 bank_reconciliations.push(recon);
2981 }
2982 }
2983 info!(
2984 "Bank reconciliations generated: {} reconciliations",
2985 bank_reconciliations.len()
2986 );
2987 }
2988
2989 stats.bank_reconciliation_count = bank_reconciliations.len();
2990 self.check_resources_with_log("post-financial-reporting")?;
2991
2992 if !trial_balances.is_empty() {
2993 info!(
2994 "Period-close trial balances captured: {} periods",
2995 trial_balances.len()
2996 );
2997 }
2998
2999 Ok(FinancialReportingSnapshot {
3000 financial_statements,
3001 bank_reconciliations,
3002 trial_balances,
3003 })
3004 }
3005
3006 fn build_trial_balance_from_entries(
3012 journal_entries: &[JournalEntry],
3013 coa: &ChartOfAccounts,
3014 company_code: &str,
3015 fiscal_year: u16,
3016 fiscal_period: u8,
3017 ) -> Vec<datasynth_generators::TrialBalanceEntry> {
3018 use rust_decimal::Decimal;
3019
3020 let mut account_debits: HashMap<String, Decimal> = HashMap::new();
3022 let mut account_credits: HashMap<String, Decimal> = HashMap::new();
3023
3024 for je in journal_entries {
3025 if je.header.company_code != company_code
3027 || je.header.fiscal_year != fiscal_year
3028 || je.header.fiscal_period != fiscal_period
3029 {
3030 continue;
3031 }
3032
3033 for line in &je.lines {
3034 let acct = &line.gl_account;
3035 *account_debits.entry(acct.clone()).or_insert(Decimal::ZERO) += line.debit_amount;
3036 *account_credits.entry(acct.clone()).or_insert(Decimal::ZERO) += line.credit_amount;
3037 }
3038 }
3039
3040 let mut all_accounts: Vec<&String> = account_debits
3042 .keys()
3043 .chain(account_credits.keys())
3044 .collect::<std::collections::HashSet<_>>()
3045 .into_iter()
3046 .collect();
3047 all_accounts.sort();
3048
3049 let mut entries = Vec::new();
3050
3051 for acct_number in all_accounts {
3052 let debit = account_debits
3053 .get(acct_number)
3054 .copied()
3055 .unwrap_or(Decimal::ZERO);
3056 let credit = account_credits
3057 .get(acct_number)
3058 .copied()
3059 .unwrap_or(Decimal::ZERO);
3060
3061 if debit.is_zero() && credit.is_zero() {
3062 continue;
3063 }
3064
3065 let account_name = coa
3067 .get_account(acct_number)
3068 .map(|gl| gl.short_description.clone())
3069 .unwrap_or_else(|| format!("Account {}", acct_number));
3070
3071 let category = Self::category_from_account_code(acct_number);
3076
3077 entries.push(datasynth_generators::TrialBalanceEntry {
3078 account_code: acct_number.clone(),
3079 account_name,
3080 category,
3081 debit_balance: debit,
3082 credit_balance: credit,
3083 });
3084 }
3085
3086 entries
3087 }
3088
3089 fn build_cumulative_trial_balance(
3096 journal_entries: &[JournalEntry],
3097 coa: &ChartOfAccounts,
3098 company_code: &str,
3099 start_date: NaiveDate,
3100 period_end: NaiveDate,
3101 fiscal_year: u16,
3102 fiscal_period: u8,
3103 ) -> Vec<datasynth_generators::TrialBalanceEntry> {
3104 use rust_decimal::Decimal;
3105
3106 let mut bs_debits: HashMap<String, Decimal> = HashMap::new();
3108 let mut bs_credits: HashMap<String, Decimal> = HashMap::new();
3109
3110 let mut is_debits: HashMap<String, Decimal> = HashMap::new();
3112 let mut is_credits: HashMap<String, Decimal> = HashMap::new();
3113
3114 for je in journal_entries {
3115 if je.header.company_code != company_code {
3116 continue;
3117 }
3118
3119 for line in &je.lines {
3120 let acct = &line.gl_account;
3121 let category = Self::category_from_account_code(acct);
3122 let is_bs_account = matches!(
3123 category.as_str(),
3124 "Cash"
3125 | "Receivables"
3126 | "Inventory"
3127 | "FixedAssets"
3128 | "Payables"
3129 | "AccruedLiabilities"
3130 | "LongTermDebt"
3131 | "Equity"
3132 );
3133
3134 if is_bs_account {
3135 if je.header.document_date <= period_end
3137 && je.header.document_date >= start_date
3138 {
3139 *bs_debits.entry(acct.clone()).or_insert(Decimal::ZERO) +=
3140 line.debit_amount;
3141 *bs_credits.entry(acct.clone()).or_insert(Decimal::ZERO) +=
3142 line.credit_amount;
3143 }
3144 } else {
3145 if je.header.fiscal_year == fiscal_year
3147 && je.header.fiscal_period == fiscal_period
3148 {
3149 *is_debits.entry(acct.clone()).or_insert(Decimal::ZERO) +=
3150 line.debit_amount;
3151 *is_credits.entry(acct.clone()).or_insert(Decimal::ZERO) +=
3152 line.credit_amount;
3153 }
3154 }
3155 }
3156 }
3157
3158 let mut all_accounts: std::collections::HashSet<String> = std::collections::HashSet::new();
3160 all_accounts.extend(bs_debits.keys().cloned());
3161 all_accounts.extend(bs_credits.keys().cloned());
3162 all_accounts.extend(is_debits.keys().cloned());
3163 all_accounts.extend(is_credits.keys().cloned());
3164
3165 let mut sorted_accounts: Vec<String> = all_accounts.into_iter().collect();
3166 sorted_accounts.sort();
3167
3168 let mut entries = Vec::new();
3169
3170 for acct_number in &sorted_accounts {
3171 let category = Self::category_from_account_code(acct_number);
3172 let is_bs_account = matches!(
3173 category.as_str(),
3174 "Cash"
3175 | "Receivables"
3176 | "Inventory"
3177 | "FixedAssets"
3178 | "Payables"
3179 | "AccruedLiabilities"
3180 | "LongTermDebt"
3181 | "Equity"
3182 );
3183
3184 let (debit, credit) = if is_bs_account {
3185 (
3186 bs_debits.get(acct_number).copied().unwrap_or(Decimal::ZERO),
3187 bs_credits
3188 .get(acct_number)
3189 .copied()
3190 .unwrap_or(Decimal::ZERO),
3191 )
3192 } else {
3193 (
3194 is_debits.get(acct_number).copied().unwrap_or(Decimal::ZERO),
3195 is_credits
3196 .get(acct_number)
3197 .copied()
3198 .unwrap_or(Decimal::ZERO),
3199 )
3200 };
3201
3202 if debit.is_zero() && credit.is_zero() {
3203 continue;
3204 }
3205
3206 let account_name = coa
3207 .get_account(acct_number)
3208 .map(|gl| gl.short_description.clone())
3209 .unwrap_or_else(|| format!("Account {}", acct_number));
3210
3211 entries.push(datasynth_generators::TrialBalanceEntry {
3212 account_code: acct_number.clone(),
3213 account_name,
3214 category,
3215 debit_balance: debit,
3216 credit_balance: credit,
3217 });
3218 }
3219
3220 entries
3221 }
3222
3223 fn build_cash_flow_from_trial_balances(
3228 current_tb: &[datasynth_generators::TrialBalanceEntry],
3229 prior_tb: Option<&[datasynth_generators::TrialBalanceEntry]>,
3230 net_income: rust_decimal::Decimal,
3231 ) -> Vec<CashFlowItem> {
3232 use rust_decimal::Decimal;
3233
3234 let aggregate =
3236 |tb: &[datasynth_generators::TrialBalanceEntry]| -> HashMap<String, Decimal> {
3237 let mut map: HashMap<String, Decimal> = HashMap::new();
3238 for entry in tb {
3239 let net = entry.debit_balance - entry.credit_balance;
3240 *map.entry(entry.category.clone()).or_default() += net;
3241 }
3242 map
3243 };
3244
3245 let current = aggregate(current_tb);
3246 let prior = prior_tb.map(aggregate);
3247
3248 let get = |map: &HashMap<String, Decimal>, key: &str| -> Decimal {
3250 *map.get(key).unwrap_or(&Decimal::ZERO)
3251 };
3252
3253 let change = |key: &str| -> Decimal {
3255 let curr = get(¤t, key);
3256 match &prior {
3257 Some(p) => curr - get(p, key),
3258 None => curr,
3259 }
3260 };
3261
3262 let fixed_asset_change = change("FixedAssets");
3265 let depreciation_addback = if fixed_asset_change < Decimal::ZERO {
3266 -fixed_asset_change
3267 } else {
3268 Decimal::ZERO
3269 };
3270
3271 let ar_change = change("Receivables");
3273 let inventory_change = change("Inventory");
3274 let ap_change = change("Payables");
3276 let accrued_change = change("AccruedLiabilities");
3277
3278 let operating_cf = net_income + depreciation_addback - ar_change - inventory_change
3279 + (-ap_change)
3280 + (-accrued_change);
3281
3282 let capex = if fixed_asset_change > Decimal::ZERO {
3284 -fixed_asset_change
3285 } else {
3286 Decimal::ZERO
3287 };
3288 let investing_cf = capex;
3289
3290 let debt_change = -change("LongTermDebt");
3292 let equity_change = -change("Equity");
3293 let financing_cf = debt_change + equity_change;
3294
3295 let net_change = operating_cf + investing_cf + financing_cf;
3296
3297 vec![
3298 CashFlowItem {
3299 item_code: "CF-NI".to_string(),
3300 label: "Net Income".to_string(),
3301 category: CashFlowCategory::Operating,
3302 amount: net_income,
3303 amount_prior: None,
3304 sort_order: 1,
3305 is_total: false,
3306 },
3307 CashFlowItem {
3308 item_code: "CF-DEP".to_string(),
3309 label: "Depreciation & Amortization".to_string(),
3310 category: CashFlowCategory::Operating,
3311 amount: depreciation_addback,
3312 amount_prior: None,
3313 sort_order: 2,
3314 is_total: false,
3315 },
3316 CashFlowItem {
3317 item_code: "CF-AR".to_string(),
3318 label: "Change in Accounts Receivable".to_string(),
3319 category: CashFlowCategory::Operating,
3320 amount: -ar_change,
3321 amount_prior: None,
3322 sort_order: 3,
3323 is_total: false,
3324 },
3325 CashFlowItem {
3326 item_code: "CF-AP".to_string(),
3327 label: "Change in Accounts Payable".to_string(),
3328 category: CashFlowCategory::Operating,
3329 amount: -ap_change,
3330 amount_prior: None,
3331 sort_order: 4,
3332 is_total: false,
3333 },
3334 CashFlowItem {
3335 item_code: "CF-INV".to_string(),
3336 label: "Change in Inventory".to_string(),
3337 category: CashFlowCategory::Operating,
3338 amount: -inventory_change,
3339 amount_prior: None,
3340 sort_order: 5,
3341 is_total: false,
3342 },
3343 CashFlowItem {
3344 item_code: "CF-OP".to_string(),
3345 label: "Net Cash from Operating Activities".to_string(),
3346 category: CashFlowCategory::Operating,
3347 amount: operating_cf,
3348 amount_prior: None,
3349 sort_order: 6,
3350 is_total: true,
3351 },
3352 CashFlowItem {
3353 item_code: "CF-CAPEX".to_string(),
3354 label: "Capital Expenditures".to_string(),
3355 category: CashFlowCategory::Investing,
3356 amount: capex,
3357 amount_prior: None,
3358 sort_order: 7,
3359 is_total: false,
3360 },
3361 CashFlowItem {
3362 item_code: "CF-INV-T".to_string(),
3363 label: "Net Cash from Investing Activities".to_string(),
3364 category: CashFlowCategory::Investing,
3365 amount: investing_cf,
3366 amount_prior: None,
3367 sort_order: 8,
3368 is_total: true,
3369 },
3370 CashFlowItem {
3371 item_code: "CF-DEBT".to_string(),
3372 label: "Net Borrowings / (Repayments)".to_string(),
3373 category: CashFlowCategory::Financing,
3374 amount: debt_change,
3375 amount_prior: None,
3376 sort_order: 9,
3377 is_total: false,
3378 },
3379 CashFlowItem {
3380 item_code: "CF-EQ".to_string(),
3381 label: "Equity Changes".to_string(),
3382 category: CashFlowCategory::Financing,
3383 amount: equity_change,
3384 amount_prior: None,
3385 sort_order: 10,
3386 is_total: false,
3387 },
3388 CashFlowItem {
3389 item_code: "CF-FIN-T".to_string(),
3390 label: "Net Cash from Financing Activities".to_string(),
3391 category: CashFlowCategory::Financing,
3392 amount: financing_cf,
3393 amount_prior: None,
3394 sort_order: 11,
3395 is_total: true,
3396 },
3397 CashFlowItem {
3398 item_code: "CF-NET".to_string(),
3399 label: "Net Change in Cash".to_string(),
3400 category: CashFlowCategory::Operating,
3401 amount: net_change,
3402 amount_prior: None,
3403 sort_order: 12,
3404 is_total: true,
3405 },
3406 ]
3407 }
3408
3409 fn calculate_net_income_from_tb(
3413 tb: &[datasynth_generators::TrialBalanceEntry],
3414 ) -> rust_decimal::Decimal {
3415 use rust_decimal::Decimal;
3416
3417 let mut aggregated: HashMap<String, Decimal> = HashMap::new();
3418 for entry in tb {
3419 let net = entry.debit_balance - entry.credit_balance;
3420 *aggregated.entry(entry.category.clone()).or_default() += net;
3421 }
3422
3423 let revenue = *aggregated.get("Revenue").unwrap_or(&Decimal::ZERO);
3424 let cogs = *aggregated.get("CostOfSales").unwrap_or(&Decimal::ZERO);
3425 let opex = *aggregated
3426 .get("OperatingExpenses")
3427 .unwrap_or(&Decimal::ZERO);
3428 let other_income = *aggregated.get("OtherIncome").unwrap_or(&Decimal::ZERO);
3429 let other_expenses = *aggregated.get("OtherExpenses").unwrap_or(&Decimal::ZERO);
3430
3431 let operating_income = revenue - cogs - opex - other_expenses - other_income;
3434 let tax_rate = Decimal::from_f64_retain(0.25).unwrap_or(Decimal::ZERO);
3435 let tax = operating_income * tax_rate;
3436 operating_income - tax
3437 }
3438
3439 fn category_from_account_code(code: &str) -> String {
3446 let prefix: String = code.chars().take(2).collect();
3447 match prefix.as_str() {
3448 "10" => "Cash",
3449 "11" => "Receivables",
3450 "12" | "13" | "14" => "Inventory",
3451 "15" | "16" | "17" | "18" | "19" => "FixedAssets",
3452 "20" => "Payables",
3453 "21" | "22" | "23" | "24" => "AccruedLiabilities",
3454 "25" | "26" | "27" | "28" | "29" => "LongTermDebt",
3455 "30" | "31" | "32" | "33" | "34" | "35" | "36" | "37" | "38" | "39" => "Equity",
3456 "40" | "41" | "42" | "43" | "44" => "Revenue",
3457 "50" | "51" | "52" => "CostOfSales",
3458 "60" | "61" | "62" | "63" | "64" | "65" | "66" | "67" | "68" | "69" => {
3459 "OperatingExpenses"
3460 }
3461 "70" | "71" | "72" | "73" | "74" => "OtherIncome",
3462 "80" | "81" | "82" | "83" | "84" | "85" | "86" | "87" | "88" | "89" => "OtherExpenses",
3463 _ => "OperatingExpenses",
3464 }
3465 .to_string()
3466 }
3467
3468 fn phase_hr_data(
3470 &mut self,
3471 stats: &mut EnhancedGenerationStatistics,
3472 ) -> SynthResult<HrSnapshot> {
3473 if !self.config.hr.enabled {
3474 debug!("Phase 16: Skipped (HR generation disabled)");
3475 return Ok(HrSnapshot::default());
3476 }
3477
3478 info!("Phase 16: Generating HR Data (Payroll, Time Entries, Expenses)");
3479
3480 let seed = self.seed;
3481 let start_date = NaiveDate::parse_from_str(&self.config.global.start_date, "%Y-%m-%d")
3482 .map_err(|e| SynthError::config(format!("Invalid start_date: {}", e)))?;
3483 let end_date = start_date + chrono::Months::new(self.config.global.period_months);
3484 let company_code = self
3485 .config
3486 .companies
3487 .first()
3488 .map(|c| c.code.as_str())
3489 .unwrap_or("1000");
3490 let currency = self
3491 .config
3492 .companies
3493 .first()
3494 .map(|c| c.currency.as_str())
3495 .unwrap_or("USD");
3496
3497 let employee_ids: Vec<String> = self
3498 .master_data
3499 .employees
3500 .iter()
3501 .map(|e| e.employee_id.clone())
3502 .collect();
3503
3504 if employee_ids.is_empty() {
3505 debug!("Phase 16: Skipped (no employees available)");
3506 return Ok(HrSnapshot::default());
3507 }
3508
3509 let cost_center_ids: Vec<String> = self
3512 .master_data
3513 .employees
3514 .iter()
3515 .filter_map(|e| e.cost_center.clone())
3516 .collect::<std::collections::HashSet<_>>()
3517 .into_iter()
3518 .collect();
3519
3520 let mut snapshot = HrSnapshot::default();
3521
3522 if self.config.hr.payroll.enabled {
3524 let mut payroll_gen = datasynth_generators::PayrollGenerator::new(seed + 30)
3525 .with_pools(employee_ids.clone(), cost_center_ids.clone());
3526
3527 let payroll_pack = self.primary_pack();
3529
3530 payroll_gen.set_country_pack(payroll_pack.clone());
3533
3534 let employees_with_salary: Vec<(
3535 String,
3536 rust_decimal::Decimal,
3537 Option<String>,
3538 Option<String>,
3539 )> = self
3540 .master_data
3541 .employees
3542 .iter()
3543 .map(|e| {
3544 (
3545 e.employee_id.clone(),
3546 rust_decimal::Decimal::from(5000), e.cost_center.clone(),
3548 e.department_id.clone(),
3549 )
3550 })
3551 .collect();
3552
3553 for month in 0..self.config.global.period_months {
3554 let period_start = start_date + chrono::Months::new(month);
3555 let period_end = start_date + chrono::Months::new(month + 1) - chrono::Days::new(1);
3556 let (run, items) = payroll_gen.generate(
3557 company_code,
3558 &employees_with_salary,
3559 period_start,
3560 period_end,
3561 currency,
3562 );
3563 snapshot.payroll_runs.push(run);
3564 snapshot.payroll_run_count += 1;
3565 snapshot.payroll_line_item_count += items.len();
3566 snapshot.payroll_line_items.extend(items);
3567 }
3568 }
3569
3570 if self.config.hr.time_attendance.enabled {
3572 let mut time_gen = datasynth_generators::TimeEntryGenerator::new(seed + 31)
3573 .with_pools(employee_ids.clone(), cost_center_ids.clone());
3574 let entries = time_gen.generate(
3575 &employee_ids,
3576 start_date,
3577 end_date,
3578 &self.config.hr.time_attendance,
3579 );
3580 snapshot.time_entry_count = entries.len();
3581 snapshot.time_entries = entries;
3582 }
3583
3584 if self.config.hr.expenses.enabled {
3586 let mut expense_gen = datasynth_generators::ExpenseReportGenerator::new(seed + 32)
3587 .with_pools(employee_ids.clone(), cost_center_ids.clone());
3588 let company_currency = self
3589 .config
3590 .companies
3591 .first()
3592 .map(|c| c.currency.as_str())
3593 .unwrap_or("USD");
3594 let reports = expense_gen.generate_with_currency(
3595 &employee_ids,
3596 start_date,
3597 end_date,
3598 &self.config.hr.expenses,
3599 company_currency,
3600 );
3601 snapshot.expense_report_count = reports.len();
3602 snapshot.expense_reports = reports;
3603 }
3604
3605 stats.payroll_run_count = snapshot.payroll_run_count;
3606 stats.time_entry_count = snapshot.time_entry_count;
3607 stats.expense_report_count = snapshot.expense_report_count;
3608
3609 info!(
3610 "HR data generated: {} payroll runs ({} line items), {} time entries, {} expense reports",
3611 snapshot.payroll_run_count, snapshot.payroll_line_item_count,
3612 snapshot.time_entry_count, snapshot.expense_report_count
3613 );
3614 self.check_resources_with_log("post-hr")?;
3615
3616 Ok(snapshot)
3617 }
3618
3619 fn phase_accounting_standards(
3621 &mut self,
3622 stats: &mut EnhancedGenerationStatistics,
3623 ) -> SynthResult<AccountingStandardsSnapshot> {
3624 if !self.phase_config.generate_accounting_standards
3625 || !self.config.accounting_standards.enabled
3626 {
3627 debug!("Phase 17: Skipped (accounting standards generation disabled)");
3628 return Ok(AccountingStandardsSnapshot::default());
3629 }
3630 info!("Phase 17: Generating Accounting Standards Data");
3631
3632 let seed = self.seed;
3633 let start_date = NaiveDate::parse_from_str(&self.config.global.start_date, "%Y-%m-%d")
3634 .map_err(|e| SynthError::config(format!("Invalid start_date: {}", e)))?;
3635 let end_date = start_date + chrono::Months::new(self.config.global.period_months);
3636 let company_code = self
3637 .config
3638 .companies
3639 .first()
3640 .map(|c| c.code.as_str())
3641 .unwrap_or("1000");
3642 let currency = self
3643 .config
3644 .companies
3645 .first()
3646 .map(|c| c.currency.as_str())
3647 .unwrap_or("USD");
3648
3649 let framework = match self.config.accounting_standards.framework {
3654 Some(datasynth_config::schema::AccountingFrameworkConfig::UsGaap) => {
3655 datasynth_standards::framework::AccountingFramework::UsGaap
3656 }
3657 Some(datasynth_config::schema::AccountingFrameworkConfig::Ifrs) => {
3658 datasynth_standards::framework::AccountingFramework::Ifrs
3659 }
3660 Some(datasynth_config::schema::AccountingFrameworkConfig::DualReporting) => {
3661 datasynth_standards::framework::AccountingFramework::DualReporting
3662 }
3663 None => {
3664 let pack = self.primary_pack();
3666 let pack_fw = pack.accounting.framework.as_str();
3667 match pack_fw {
3668 "ifrs" => datasynth_standards::framework::AccountingFramework::Ifrs,
3669 "dual_reporting" => {
3670 datasynth_standards::framework::AccountingFramework::DualReporting
3671 }
3672 _ => datasynth_standards::framework::AccountingFramework::UsGaap,
3674 }
3675 }
3676 };
3677
3678 let mut snapshot = AccountingStandardsSnapshot::default();
3679
3680 if self.config.accounting_standards.revenue_recognition.enabled {
3682 let customer_ids: Vec<String> = self
3683 .master_data
3684 .customers
3685 .iter()
3686 .map(|c| c.customer_id.clone())
3687 .collect();
3688
3689 if !customer_ids.is_empty() {
3690 let mut rev_gen = datasynth_generators::RevenueRecognitionGenerator::new(seed + 40);
3691 let contracts = rev_gen.generate(
3692 company_code,
3693 &customer_ids,
3694 start_date,
3695 end_date,
3696 currency,
3697 &self.config.accounting_standards.revenue_recognition,
3698 framework,
3699 );
3700 snapshot.revenue_contract_count = contracts.len();
3701 snapshot.contracts = contracts;
3702 }
3703 }
3704
3705 if self.config.accounting_standards.impairment.enabled {
3707 let asset_data: Vec<(String, String, rust_decimal::Decimal)> = self
3708 .master_data
3709 .assets
3710 .iter()
3711 .map(|a| {
3712 (
3713 a.asset_id.clone(),
3714 a.description.clone(),
3715 a.acquisition_cost,
3716 )
3717 })
3718 .collect();
3719
3720 if !asset_data.is_empty() {
3721 let mut imp_gen = datasynth_generators::ImpairmentGenerator::new(seed + 41);
3722 let tests = imp_gen.generate(
3723 company_code,
3724 &asset_data,
3725 end_date,
3726 &self.config.accounting_standards.impairment,
3727 framework,
3728 );
3729 snapshot.impairment_test_count = tests.len();
3730 snapshot.impairment_tests = tests;
3731 }
3732 }
3733
3734 stats.revenue_contract_count = snapshot.revenue_contract_count;
3735 stats.impairment_test_count = snapshot.impairment_test_count;
3736
3737 info!(
3738 "Accounting standards data generated: {} revenue contracts, {} impairment tests",
3739 snapshot.revenue_contract_count, snapshot.impairment_test_count
3740 );
3741 self.check_resources_with_log("post-accounting-standards")?;
3742
3743 Ok(snapshot)
3744 }
3745
3746 fn phase_manufacturing(
3748 &mut self,
3749 stats: &mut EnhancedGenerationStatistics,
3750 ) -> SynthResult<ManufacturingSnapshot> {
3751 if !self.phase_config.generate_manufacturing || !self.config.manufacturing.enabled {
3752 debug!("Phase 18: Skipped (manufacturing generation disabled)");
3753 return Ok(ManufacturingSnapshot::default());
3754 }
3755 info!("Phase 18: Generating Manufacturing Data");
3756
3757 let seed = self.seed;
3758 let start_date = NaiveDate::parse_from_str(&self.config.global.start_date, "%Y-%m-%d")
3759 .map_err(|e| SynthError::config(format!("Invalid start_date: {}", e)))?;
3760 let end_date = start_date + chrono::Months::new(self.config.global.period_months);
3761 let company_code = self
3762 .config
3763 .companies
3764 .first()
3765 .map(|c| c.code.as_str())
3766 .unwrap_or("1000");
3767
3768 let material_data: Vec<(String, String)> = self
3769 .master_data
3770 .materials
3771 .iter()
3772 .map(|m| (m.material_id.clone(), m.description.clone()))
3773 .collect();
3774
3775 if material_data.is_empty() {
3776 debug!("Phase 18: Skipped (no materials available)");
3777 return Ok(ManufacturingSnapshot::default());
3778 }
3779
3780 let mut snapshot = ManufacturingSnapshot::default();
3781
3782 let mut prod_gen = datasynth_generators::ProductionOrderGenerator::new(seed + 50);
3784 let production_orders = prod_gen.generate(
3785 company_code,
3786 &material_data,
3787 start_date,
3788 end_date,
3789 &self.config.manufacturing.production_orders,
3790 &self.config.manufacturing.costing,
3791 &self.config.manufacturing.routing,
3792 );
3793 snapshot.production_order_count = production_orders.len();
3794
3795 let inspection_data: Vec<(String, String, String)> = production_orders
3797 .iter()
3798 .map(|po| {
3799 (
3800 po.order_id.clone(),
3801 po.material_id.clone(),
3802 po.material_description.clone(),
3803 )
3804 })
3805 .collect();
3806
3807 snapshot.production_orders = production_orders;
3808
3809 if !inspection_data.is_empty() {
3810 let mut qi_gen = datasynth_generators::QualityInspectionGenerator::new(seed + 51);
3811 let inspections = qi_gen.generate(company_code, &inspection_data, end_date);
3812 snapshot.quality_inspection_count = inspections.len();
3813 snapshot.quality_inspections = inspections;
3814 }
3815
3816 let storage_locations: Vec<(String, String)> = material_data
3818 .iter()
3819 .enumerate()
3820 .map(|(i, (mid, _))| (mid.clone(), format!("SL-{:03}", (i % 10) + 1)))
3821 .collect();
3822
3823 let employee_ids: Vec<String> = self
3824 .master_data
3825 .employees
3826 .iter()
3827 .map(|e| e.employee_id.clone())
3828 .collect();
3829 let mut cc_gen = datasynth_generators::CycleCountGenerator::new(seed + 52)
3830 .with_employee_pool(employee_ids);
3831 let mut cycle_count_total = 0usize;
3832 for month in 0..self.config.global.period_months {
3833 let count_date = start_date + chrono::Months::new(month);
3834 let items_per_count = storage_locations.len().clamp(10, 50);
3835 let cc = cc_gen.generate(
3836 company_code,
3837 &storage_locations,
3838 count_date,
3839 items_per_count,
3840 );
3841 snapshot.cycle_counts.push(cc);
3842 cycle_count_total += 1;
3843 }
3844 snapshot.cycle_count_count = cycle_count_total;
3845
3846 stats.production_order_count = snapshot.production_order_count;
3847 stats.quality_inspection_count = snapshot.quality_inspection_count;
3848 stats.cycle_count_count = snapshot.cycle_count_count;
3849
3850 info!(
3851 "Manufacturing data generated: {} production orders, {} quality inspections, {} cycle counts",
3852 snapshot.production_order_count, snapshot.quality_inspection_count, snapshot.cycle_count_count
3853 );
3854 self.check_resources_with_log("post-manufacturing")?;
3855
3856 Ok(snapshot)
3857 }
3858
3859 fn phase_sales_kpi_budgets(
3861 &mut self,
3862 coa: &Arc<ChartOfAccounts>,
3863 financial_reporting: &FinancialReportingSnapshot,
3864 stats: &mut EnhancedGenerationStatistics,
3865 ) -> SynthResult<SalesKpiBudgetsSnapshot> {
3866 if !self.phase_config.generate_sales_kpi_budgets {
3867 debug!("Phase 19: Skipped (sales/KPI/budget generation disabled)");
3868 return Ok(SalesKpiBudgetsSnapshot::default());
3869 }
3870 info!("Phase 19: Generating Sales Quotes, KPIs, and Budgets");
3871
3872 let seed = self.seed;
3873 let start_date = NaiveDate::parse_from_str(&self.config.global.start_date, "%Y-%m-%d")
3874 .map_err(|e| SynthError::config(format!("Invalid start_date: {}", e)))?;
3875 let end_date = start_date + chrono::Months::new(self.config.global.period_months);
3876 let company_code = self
3877 .config
3878 .companies
3879 .first()
3880 .map(|c| c.code.as_str())
3881 .unwrap_or("1000");
3882
3883 let mut snapshot = SalesKpiBudgetsSnapshot::default();
3884
3885 if self.config.sales_quotes.enabled {
3887 let customer_data: Vec<(String, String)> = self
3888 .master_data
3889 .customers
3890 .iter()
3891 .map(|c| (c.customer_id.clone(), c.name.clone()))
3892 .collect();
3893 let material_data: Vec<(String, String)> = self
3894 .master_data
3895 .materials
3896 .iter()
3897 .map(|m| (m.material_id.clone(), m.description.clone()))
3898 .collect();
3899
3900 if !customer_data.is_empty() && !material_data.is_empty() {
3901 let employee_ids: Vec<String> = self
3902 .master_data
3903 .employees
3904 .iter()
3905 .map(|e| e.employee_id.clone())
3906 .collect();
3907 let customer_ids: Vec<String> = self
3908 .master_data
3909 .customers
3910 .iter()
3911 .map(|c| c.customer_id.clone())
3912 .collect();
3913 let company_currency = self
3914 .config
3915 .companies
3916 .first()
3917 .map(|c| c.currency.as_str())
3918 .unwrap_or("USD");
3919
3920 let mut quote_gen = datasynth_generators::SalesQuoteGenerator::new(seed + 60)
3921 .with_pools(employee_ids, customer_ids);
3922 let quotes = quote_gen.generate_with_currency(
3923 company_code,
3924 &customer_data,
3925 &material_data,
3926 start_date,
3927 end_date,
3928 &self.config.sales_quotes,
3929 company_currency,
3930 );
3931 snapshot.sales_quote_count = quotes.len();
3932 snapshot.sales_quotes = quotes;
3933 }
3934 }
3935
3936 if self.config.financial_reporting.management_kpis.enabled {
3938 let mut kpi_gen = datasynth_generators::KpiGenerator::new(seed + 61);
3939 let mut kpis = kpi_gen.generate(
3940 company_code,
3941 start_date,
3942 end_date,
3943 &self.config.financial_reporting.management_kpis,
3944 );
3945
3946 {
3948 use rust_decimal::Decimal;
3949
3950 if let Some(income_stmt) =
3951 financial_reporting.financial_statements.iter().find(|fs| {
3952 fs.statement_type == StatementType::IncomeStatement
3953 && fs.company_code == company_code
3954 })
3955 {
3956 let total_revenue: Decimal = income_stmt
3958 .line_items
3959 .iter()
3960 .filter(|li| li.section.contains("Revenue") && !li.is_total)
3961 .map(|li| li.amount)
3962 .sum();
3963 let total_cogs: Decimal = income_stmt
3964 .line_items
3965 .iter()
3966 .filter(|li| {
3967 (li.section.contains("Cost") || li.line_code.starts_with("IS-COGS"))
3968 && !li.is_total
3969 })
3970 .map(|li| li.amount.abs())
3971 .sum();
3972 let total_opex: Decimal = income_stmt
3973 .line_items
3974 .iter()
3975 .filter(|li| {
3976 li.section.contains("Expense")
3977 && !li.is_total
3978 && !li.section.contains("Cost")
3979 })
3980 .map(|li| li.amount.abs())
3981 .sum();
3982
3983 if total_revenue > Decimal::ZERO {
3984 let hundred = Decimal::from(100);
3985 let gross_margin_pct =
3986 ((total_revenue - total_cogs) * hundred / total_revenue).round_dp(2);
3987 let operating_income = total_revenue - total_cogs - total_opex;
3988 let op_margin_pct =
3989 (operating_income * hundred / total_revenue).round_dp(2);
3990
3991 for kpi in &mut kpis {
3993 if kpi.name == "Gross Margin" {
3994 kpi.value = gross_margin_pct;
3995 } else if kpi.name == "Operating Margin" {
3996 kpi.value = op_margin_pct;
3997 }
3998 }
3999 }
4000 }
4001
4002 if let Some(bs) = financial_reporting.financial_statements.iter().find(|fs| {
4004 fs.statement_type == StatementType::BalanceSheet
4005 && fs.company_code == company_code
4006 }) {
4007 let current_assets: Decimal = bs
4008 .line_items
4009 .iter()
4010 .filter(|li| li.section.contains("Current Assets") && !li.is_total)
4011 .map(|li| li.amount)
4012 .sum();
4013 let current_liabilities: Decimal = bs
4014 .line_items
4015 .iter()
4016 .filter(|li| li.section.contains("Current Liabilities") && !li.is_total)
4017 .map(|li| li.amount.abs())
4018 .sum();
4019
4020 if current_liabilities > Decimal::ZERO {
4021 let current_ratio = (current_assets / current_liabilities).round_dp(2);
4022 for kpi in &mut kpis {
4023 if kpi.name == "Current Ratio" {
4024 kpi.value = current_ratio;
4025 }
4026 }
4027 }
4028 }
4029 }
4030
4031 snapshot.kpi_count = kpis.len();
4032 snapshot.kpis = kpis;
4033 }
4034
4035 if self.config.financial_reporting.budgets.enabled {
4037 let account_data: Vec<(String, String)> = coa
4038 .accounts
4039 .iter()
4040 .map(|a| (a.account_number.clone(), a.short_description.clone()))
4041 .collect();
4042
4043 if !account_data.is_empty() {
4044 let fiscal_year = start_date.year() as u32;
4045 let mut budget_gen = datasynth_generators::BudgetGenerator::new(seed + 62);
4046 let budget = budget_gen.generate(
4047 company_code,
4048 fiscal_year,
4049 &account_data,
4050 &self.config.financial_reporting.budgets,
4051 );
4052 snapshot.budget_line_count = budget.line_items.len();
4053 snapshot.budgets.push(budget);
4054 }
4055 }
4056
4057 stats.sales_quote_count = snapshot.sales_quote_count;
4058 stats.kpi_count = snapshot.kpi_count;
4059 stats.budget_line_count = snapshot.budget_line_count;
4060
4061 info!(
4062 "Sales/KPI/Budget data generated: {} quotes, {} KPIs, {} budget lines",
4063 snapshot.sales_quote_count, snapshot.kpi_count, snapshot.budget_line_count
4064 );
4065 self.check_resources_with_log("post-sales-kpi-budgets")?;
4066
4067 Ok(snapshot)
4068 }
4069
4070 fn phase_tax_generation(
4072 &mut self,
4073 document_flows: &DocumentFlowSnapshot,
4074 stats: &mut EnhancedGenerationStatistics,
4075 ) -> SynthResult<TaxSnapshot> {
4076 if !self.phase_config.generate_tax || !self.config.tax.enabled {
4077 debug!("Phase 20: Skipped (tax generation disabled)");
4078 return Ok(TaxSnapshot::default());
4079 }
4080 info!("Phase 20: Generating Tax Data");
4081
4082 let seed = self.seed;
4083 let start_date = NaiveDate::parse_from_str(&self.config.global.start_date, "%Y-%m-%d")
4084 .map_err(|e| SynthError::config(format!("Invalid start_date: {}", e)))?;
4085 let fiscal_year = start_date.year();
4086 let company_code = self
4087 .config
4088 .companies
4089 .first()
4090 .map(|c| c.code.as_str())
4091 .unwrap_or("1000");
4092
4093 let mut gen =
4094 datasynth_generators::TaxCodeGenerator::with_config(seed + 70, self.config.tax.clone());
4095
4096 let pack = self.primary_pack().clone();
4097 let (jurisdictions, codes) =
4098 gen.generate_from_country_pack(&pack, company_code, fiscal_year);
4099
4100 let mut provisions = Vec::new();
4102 if self.config.tax.provisions.enabled {
4103 let mut provision_gen = datasynth_generators::TaxProvisionGenerator::new(seed + 71);
4104 for company in &self.config.companies {
4105 let pre_tax_income = rust_decimal::Decimal::from(1_000_000);
4106 let statutory_rate = rust_decimal::Decimal::new(
4107 (self.config.tax.provisions.statutory_rate * 100.0) as i64,
4108 2,
4109 );
4110 let provision = provision_gen.generate(
4111 &company.code,
4112 start_date,
4113 pre_tax_income,
4114 statutory_rate,
4115 );
4116 provisions.push(provision);
4117 }
4118 }
4119
4120 let mut tax_lines = Vec::new();
4122 if !codes.is_empty() {
4123 let mut tax_line_gen = datasynth_generators::TaxLineGenerator::new(
4124 datasynth_generators::TaxLineGeneratorConfig::default(),
4125 codes.clone(),
4126 seed + 72,
4127 );
4128
4129 let buyer_country = self
4132 .config
4133 .companies
4134 .first()
4135 .map(|c| c.country.as_str())
4136 .unwrap_or("US");
4137 for vi in &document_flows.vendor_invoices {
4138 let lines = tax_line_gen.generate_for_document(
4139 datasynth_core::models::TaxableDocumentType::VendorInvoice,
4140 &vi.header.document_id,
4141 buyer_country, buyer_country,
4143 vi.payable_amount,
4144 vi.header.document_date,
4145 None,
4146 );
4147 tax_lines.extend(lines);
4148 }
4149
4150 for ci in &document_flows.customer_invoices {
4152 let lines = tax_line_gen.generate_for_document(
4153 datasynth_core::models::TaxableDocumentType::CustomerInvoice,
4154 &ci.header.document_id,
4155 buyer_country, buyer_country,
4157 ci.total_gross_amount,
4158 ci.header.document_date,
4159 None,
4160 );
4161 tax_lines.extend(lines);
4162 }
4163 }
4164
4165 let snapshot = TaxSnapshot {
4166 jurisdiction_count: jurisdictions.len(),
4167 code_count: codes.len(),
4168 jurisdictions,
4169 codes,
4170 tax_provisions: provisions,
4171 tax_lines,
4172 tax_returns: Vec::new(),
4173 withholding_records: Vec::new(),
4174 tax_anomaly_labels: Vec::new(),
4175 };
4176
4177 stats.tax_jurisdiction_count = snapshot.jurisdiction_count;
4178 stats.tax_code_count = snapshot.code_count;
4179 stats.tax_provision_count = snapshot.tax_provisions.len();
4180 stats.tax_line_count = snapshot.tax_lines.len();
4181
4182 info!(
4183 "Tax data generated: {} jurisdictions, {} codes, {} provisions",
4184 snapshot.jurisdiction_count,
4185 snapshot.code_count,
4186 snapshot.tax_provisions.len()
4187 );
4188 self.check_resources_with_log("post-tax")?;
4189
4190 Ok(snapshot)
4191 }
4192
4193 fn phase_esg_generation(
4195 &mut self,
4196 document_flows: &DocumentFlowSnapshot,
4197 stats: &mut EnhancedGenerationStatistics,
4198 ) -> SynthResult<EsgSnapshot> {
4199 if !self.phase_config.generate_esg || !self.config.esg.enabled {
4200 debug!("Phase 21: Skipped (ESG generation disabled)");
4201 return Ok(EsgSnapshot::default());
4202 }
4203 info!("Phase 21: Generating ESG Data");
4204
4205 let seed = self.seed;
4206 let start_date = NaiveDate::parse_from_str(&self.config.global.start_date, "%Y-%m-%d")
4207 .map_err(|e| SynthError::config(format!("Invalid start_date: {}", e)))?;
4208 let end_date = start_date + chrono::Months::new(self.config.global.period_months);
4209 let entity_id = self
4210 .config
4211 .companies
4212 .first()
4213 .map(|c| c.code.as_str())
4214 .unwrap_or("1000");
4215
4216 let esg_cfg = &self.config.esg;
4217 let mut snapshot = EsgSnapshot::default();
4218
4219 let mut energy_gen = datasynth_generators::EnergyGenerator::new(
4221 esg_cfg.environmental.energy.clone(),
4222 seed + 80,
4223 );
4224 let energy_records = energy_gen.generate(entity_id, start_date, end_date);
4225
4226 let facility_count = esg_cfg.environmental.energy.facility_count;
4228 let mut water_gen = datasynth_generators::WaterGenerator::new(seed + 81, facility_count);
4229 snapshot.water = water_gen.generate(entity_id, start_date, end_date);
4230
4231 let mut waste_gen = datasynth_generators::WasteGenerator::new(
4233 seed + 82,
4234 esg_cfg.environmental.waste.diversion_target,
4235 facility_count,
4236 );
4237 snapshot.waste = waste_gen.generate(entity_id, start_date, end_date);
4238
4239 let mut emission_gen =
4241 datasynth_generators::EmissionGenerator::new(esg_cfg.environmental.clone(), seed + 83);
4242
4243 let energy_inputs: Vec<datasynth_generators::EnergyInput> = energy_records
4245 .iter()
4246 .map(|e| datasynth_generators::EnergyInput {
4247 facility_id: e.facility_id.clone(),
4248 energy_type: match e.energy_source {
4249 EnergySourceType::NaturalGas => {
4250 datasynth_generators::EnergyInputType::NaturalGas
4251 }
4252 EnergySourceType::Diesel => datasynth_generators::EnergyInputType::Diesel,
4253 EnergySourceType::Coal => datasynth_generators::EnergyInputType::Coal,
4254 _ => datasynth_generators::EnergyInputType::Electricity,
4255 },
4256 consumption_kwh: e.consumption_kwh,
4257 period: e.period,
4258 })
4259 .collect();
4260
4261 let mut emissions = Vec::new();
4262 emissions.extend(emission_gen.generate_scope1(entity_id, &energy_inputs));
4263 emissions.extend(emission_gen.generate_scope2(entity_id, &energy_inputs));
4264
4265 let vendor_payment_totals: HashMap<String, rust_decimal::Decimal> = {
4267 let mut totals: HashMap<String, rust_decimal::Decimal> = HashMap::new();
4268 for payment in &document_flows.payments {
4269 if payment.is_vendor {
4270 *totals
4271 .entry(payment.business_partner_id.clone())
4272 .or_default() += payment.amount;
4273 }
4274 }
4275 totals
4276 };
4277 let vendor_spend: Vec<datasynth_generators::VendorSpendInput> = self
4278 .master_data
4279 .vendors
4280 .iter()
4281 .map(|v| {
4282 let spend = vendor_payment_totals
4283 .get(&v.vendor_id)
4284 .copied()
4285 .unwrap_or_else(|| rust_decimal::Decimal::new(10000, 0));
4286 datasynth_generators::VendorSpendInput {
4287 vendor_id: v.vendor_id.clone(),
4288 category: format!("{:?}", v.vendor_type).to_lowercase(),
4289 spend,
4290 country: v.country.clone(),
4291 }
4292 })
4293 .collect();
4294 if !vendor_spend.is_empty() {
4295 emissions.extend(emission_gen.generate_scope3_purchased_goods(
4296 entity_id,
4297 &vendor_spend,
4298 start_date,
4299 end_date,
4300 ));
4301 }
4302
4303 let headcount = self.master_data.employees.len() as u32;
4305 if headcount > 0 {
4306 let travel_spend = rust_decimal::Decimal::new(headcount as i64 * 2000, 0);
4307 emissions.extend(emission_gen.generate_scope3_business_travel(
4308 entity_id,
4309 travel_spend,
4310 start_date,
4311 ));
4312 emissions
4313 .extend(emission_gen.generate_scope3_commuting(entity_id, headcount, start_date));
4314 }
4315
4316 snapshot.emission_count = emissions.len();
4317 snapshot.emissions = emissions;
4318 snapshot.energy = energy_records;
4319
4320 let mut workforce_gen =
4322 datasynth_generators::WorkforceGenerator::new(esg_cfg.social.clone(), seed + 84);
4323 let total_headcount = headcount.max(100);
4324 snapshot.diversity =
4325 workforce_gen.generate_diversity(entity_id, total_headcount, start_date);
4326 snapshot.pay_equity = workforce_gen.generate_pay_equity(entity_id, start_date);
4327 snapshot.safety_incidents = workforce_gen.generate_safety_incidents(
4328 entity_id,
4329 facility_count,
4330 start_date,
4331 end_date,
4332 );
4333
4334 let total_hours = total_headcount as u64 * 2000; let safety_metric = workforce_gen.compute_safety_metrics(
4337 entity_id,
4338 &snapshot.safety_incidents,
4339 total_hours,
4340 start_date,
4341 );
4342 snapshot.safety_metrics = vec![safety_metric];
4343
4344 let mut gov_gen = datasynth_generators::GovernanceGenerator::new(
4346 seed + 85,
4347 esg_cfg.governance.board_size,
4348 esg_cfg.governance.independence_target,
4349 );
4350 snapshot.governance = vec![gov_gen.generate(entity_id, start_date)];
4351
4352 let mut supplier_gen = datasynth_generators::SupplierEsgGenerator::new(
4354 esg_cfg.supply_chain_esg.clone(),
4355 seed + 86,
4356 );
4357 let vendor_inputs: Vec<datasynth_generators::VendorInput> = self
4358 .master_data
4359 .vendors
4360 .iter()
4361 .map(|v| datasynth_generators::VendorInput {
4362 vendor_id: v.vendor_id.clone(),
4363 country: v.country.clone(),
4364 industry: format!("{:?}", v.vendor_type).to_lowercase(),
4365 quality_score: None,
4366 })
4367 .collect();
4368 snapshot.supplier_assessments =
4369 supplier_gen.generate(entity_id, &vendor_inputs, start_date);
4370
4371 let mut disclosure_gen = datasynth_generators::DisclosureGenerator::new(
4373 seed + 87,
4374 esg_cfg.reporting.clone(),
4375 esg_cfg.climate_scenarios.clone(),
4376 );
4377 snapshot.materiality = disclosure_gen.generate_materiality(entity_id, start_date);
4378 snapshot.disclosures = disclosure_gen.generate_disclosures(
4379 entity_id,
4380 &snapshot.materiality,
4381 start_date,
4382 end_date,
4383 );
4384 snapshot.climate_scenarios = disclosure_gen.generate_climate_scenarios(entity_id);
4385 snapshot.disclosure_count = snapshot.disclosures.len();
4386
4387 if esg_cfg.anomaly_rate > 0.0 {
4389 let mut anomaly_injector =
4390 datasynth_generators::EsgAnomalyInjector::new(seed + 88, esg_cfg.anomaly_rate);
4391 let mut labels = Vec::new();
4392 labels.extend(anomaly_injector.inject_greenwashing(&mut snapshot.emissions));
4393 labels.extend(anomaly_injector.inject_diversity_stagnation(&mut snapshot.diversity));
4394 labels.extend(
4395 anomaly_injector.inject_supply_chain_risk(&mut snapshot.supplier_assessments),
4396 );
4397 labels.extend(anomaly_injector.inject_data_quality_gaps(&mut snapshot.safety_metrics));
4398 labels.extend(anomaly_injector.inject_missing_disclosures(&mut snapshot.materiality));
4399 snapshot.anomaly_labels = labels;
4400 }
4401
4402 stats.esg_emission_count = snapshot.emission_count;
4403 stats.esg_disclosure_count = snapshot.disclosure_count;
4404
4405 info!(
4406 "ESG data generated: {} emissions, {} disclosures, {} supplier assessments",
4407 snapshot.emission_count,
4408 snapshot.disclosure_count,
4409 snapshot.supplier_assessments.len()
4410 );
4411 self.check_resources_with_log("post-esg")?;
4412
4413 Ok(snapshot)
4414 }
4415
4416 fn phase_treasury_data(
4418 &mut self,
4419 document_flows: &DocumentFlowSnapshot,
4420 stats: &mut EnhancedGenerationStatistics,
4421 ) -> SynthResult<TreasurySnapshot> {
4422 if !self.config.treasury.enabled {
4423 debug!("Phase 22: Skipped (treasury generation disabled)");
4424 return Ok(TreasurySnapshot::default());
4425 }
4426 info!("Phase 22: Generating Treasury Data");
4427
4428 let seed = self.seed;
4429 let start_date = NaiveDate::parse_from_str(&self.config.global.start_date, "%Y-%m-%d")
4430 .map_err(|e| SynthError::config(format!("Invalid start_date: {}", e)))?;
4431 let currency = self
4432 .config
4433 .companies
4434 .first()
4435 .map(|c| c.currency.as_str())
4436 .unwrap_or("USD");
4437 let entity_id = self
4438 .config
4439 .companies
4440 .first()
4441 .map(|c| c.code.as_str())
4442 .unwrap_or("1000");
4443
4444 let mut snapshot = TreasurySnapshot::default();
4445
4446 let mut debt_gen = datasynth_generators::treasury::DebtGenerator::new(
4448 self.config.treasury.debt.clone(),
4449 seed + 90,
4450 );
4451 snapshot.debt_instruments = debt_gen.generate(entity_id, currency, start_date);
4452
4453 let mut hedge_gen = datasynth_generators::treasury::HedgingGenerator::new(
4455 self.config.treasury.hedging.clone(),
4456 seed + 91,
4457 );
4458 for debt in &snapshot.debt_instruments {
4459 if debt.rate_type == InterestRateType::Variable {
4460 let swap = hedge_gen.generate_ir_swap(
4461 currency,
4462 debt.principal,
4463 debt.origination_date,
4464 debt.maturity_date,
4465 );
4466 snapshot.hedging_instruments.push(swap);
4467 }
4468 }
4469
4470 {
4473 let mut fx_map: HashMap<String, (rust_decimal::Decimal, NaiveDate)> = HashMap::new();
4474 for payment in &document_flows.payments {
4475 if payment.currency != currency {
4476 let entry = fx_map
4477 .entry(payment.currency.clone())
4478 .or_insert((rust_decimal::Decimal::ZERO, payment.header.document_date));
4479 entry.0 += payment.amount;
4480 if payment.header.document_date > entry.1 {
4482 entry.1 = payment.header.document_date;
4483 }
4484 }
4485 }
4486 if !fx_map.is_empty() {
4487 let fx_exposures: Vec<datasynth_generators::treasury::FxExposure> = fx_map
4488 .into_iter()
4489 .map(|(foreign_ccy, (net_amount, settlement_date))| {
4490 datasynth_generators::treasury::FxExposure {
4491 currency_pair: format!("{}/{}", foreign_ccy, currency),
4492 foreign_currency: foreign_ccy,
4493 net_amount,
4494 settlement_date,
4495 description: "AP payment FX exposure".to_string(),
4496 }
4497 })
4498 .collect();
4499 let (fx_instruments, fx_relationships) =
4500 hedge_gen.generate(start_date, &fx_exposures);
4501 snapshot.hedging_instruments.extend(fx_instruments);
4502 snapshot.hedge_relationships.extend(fx_relationships);
4503 }
4504 }
4505
4506 if self.config.treasury.anomaly_rate > 0.0 {
4508 let mut anomaly_injector = datasynth_generators::treasury::TreasuryAnomalyInjector::new(
4509 seed + 92,
4510 self.config.treasury.anomaly_rate,
4511 );
4512 let mut labels = Vec::new();
4513 labels.extend(
4514 anomaly_injector.inject_into_hedge_relationships(&mut snapshot.hedge_relationships),
4515 );
4516 snapshot.treasury_anomaly_labels = labels;
4517 }
4518
4519 if self.config.treasury.cash_positioning.enabled {
4521 let mut cash_flows: Vec<datasynth_generators::treasury::CashFlow> = Vec::new();
4522
4523 for payment in &document_flows.payments {
4525 cash_flows.push(datasynth_generators::treasury::CashFlow {
4526 date: payment.header.document_date,
4527 account_id: format!("{}-MAIN", entity_id),
4528 amount: payment.amount,
4529 direction: datasynth_generators::treasury::CashFlowDirection::Outflow,
4530 });
4531 }
4532
4533 for chain in &document_flows.o2c_chains {
4535 if let Some(ref receipt) = chain.customer_receipt {
4536 cash_flows.push(datasynth_generators::treasury::CashFlow {
4537 date: receipt.header.document_date,
4538 account_id: format!("{}-MAIN", entity_id),
4539 amount: receipt.amount,
4540 direction: datasynth_generators::treasury::CashFlowDirection::Inflow,
4541 });
4542 }
4543 }
4544
4545 if !cash_flows.is_empty() {
4546 let mut cash_gen = datasynth_generators::treasury::CashPositionGenerator::new(
4547 self.config.treasury.cash_positioning.clone(),
4548 seed + 93,
4549 );
4550 let account_id = format!("{}-MAIN", entity_id);
4551 snapshot.cash_positions = cash_gen.generate(
4552 entity_id,
4553 &account_id,
4554 currency,
4555 &cash_flows,
4556 start_date,
4557 start_date + chrono::Months::new(self.config.global.period_months),
4558 rust_decimal::Decimal::new(1_000_000, 0), );
4560 }
4561 }
4562
4563 stats.treasury_debt_instrument_count = snapshot.debt_instruments.len();
4564 stats.treasury_hedging_instrument_count = snapshot.hedging_instruments.len();
4565 stats.cash_position_count = snapshot.cash_positions.len();
4566
4567 info!(
4568 "Treasury data generated: {} debt instruments, {} hedging instruments, {} cash positions",
4569 snapshot.debt_instruments.len(),
4570 snapshot.hedging_instruments.len(),
4571 snapshot.cash_positions.len()
4572 );
4573 self.check_resources_with_log("post-treasury")?;
4574
4575 Ok(snapshot)
4576 }
4577
4578 fn phase_project_accounting(
4580 &mut self,
4581 document_flows: &DocumentFlowSnapshot,
4582 hr: &HrSnapshot,
4583 stats: &mut EnhancedGenerationStatistics,
4584 ) -> SynthResult<ProjectAccountingSnapshot> {
4585 if !self.config.project_accounting.enabled {
4586 debug!("Phase 23: Skipped (project accounting disabled)");
4587 return Ok(ProjectAccountingSnapshot::default());
4588 }
4589 info!("Phase 23: Generating Project Accounting Data");
4590
4591 let seed = self.seed;
4592 let start_date = NaiveDate::parse_from_str(&self.config.global.start_date, "%Y-%m-%d")
4593 .map_err(|e| SynthError::config(format!("Invalid start_date: {}", e)))?;
4594 let end_date = start_date + chrono::Months::new(self.config.global.period_months);
4595 let company_code = self
4596 .config
4597 .companies
4598 .first()
4599 .map(|c| c.code.as_str())
4600 .unwrap_or("1000");
4601
4602 let mut snapshot = ProjectAccountingSnapshot::default();
4603
4604 let mut project_gen = datasynth_generators::project_accounting::ProjectGenerator::new(
4606 self.config.project_accounting.clone(),
4607 seed + 95,
4608 );
4609 let pool = project_gen.generate(company_code, start_date, end_date);
4610 snapshot.projects = pool.projects.clone();
4611
4612 {
4614 let mut source_docs: Vec<datasynth_generators::project_accounting::SourceDocument> =
4615 Vec::new();
4616
4617 for te in &hr.time_entries {
4619 let total_hours = te.hours_regular + te.hours_overtime;
4620 if total_hours > 0.0 {
4621 source_docs.push(datasynth_generators::project_accounting::SourceDocument {
4622 id: te.entry_id.clone(),
4623 entity_id: company_code.to_string(),
4624 date: te.date,
4625 amount: rust_decimal::Decimal::from_f64_retain(total_hours * 75.0)
4626 .unwrap_or(rust_decimal::Decimal::ZERO),
4627 source_type: CostSourceType::TimeEntry,
4628 hours: Some(
4629 rust_decimal::Decimal::from_f64_retain(total_hours)
4630 .unwrap_or(rust_decimal::Decimal::ZERO),
4631 ),
4632 });
4633 }
4634 }
4635
4636 for er in &hr.expense_reports {
4638 source_docs.push(datasynth_generators::project_accounting::SourceDocument {
4639 id: er.report_id.clone(),
4640 entity_id: company_code.to_string(),
4641 date: er.submission_date,
4642 amount: er.total_amount,
4643 source_type: CostSourceType::ExpenseReport,
4644 hours: None,
4645 });
4646 }
4647
4648 for po in &document_flows.purchase_orders {
4650 source_docs.push(datasynth_generators::project_accounting::SourceDocument {
4651 id: po.header.document_id.clone(),
4652 entity_id: company_code.to_string(),
4653 date: po.header.document_date,
4654 amount: po.total_net_amount,
4655 source_type: CostSourceType::PurchaseOrder,
4656 hours: None,
4657 });
4658 }
4659
4660 for vi in &document_flows.vendor_invoices {
4662 source_docs.push(datasynth_generators::project_accounting::SourceDocument {
4663 id: vi.header.document_id.clone(),
4664 entity_id: company_code.to_string(),
4665 date: vi.header.document_date,
4666 amount: vi.payable_amount,
4667 source_type: CostSourceType::VendorInvoice,
4668 hours: None,
4669 });
4670 }
4671
4672 if !source_docs.is_empty() && !pool.projects.is_empty() {
4673 let mut cost_gen =
4674 datasynth_generators::project_accounting::ProjectCostGenerator::new(
4675 self.config.project_accounting.cost_allocation.clone(),
4676 seed + 99,
4677 );
4678 snapshot.cost_lines = cost_gen.link_documents(&pool, &source_docs);
4679 }
4680 }
4681
4682 if self.config.project_accounting.change_orders.enabled {
4684 let mut co_gen = datasynth_generators::project_accounting::ChangeOrderGenerator::new(
4685 self.config.project_accounting.change_orders.clone(),
4686 seed + 96,
4687 );
4688 snapshot.change_orders = co_gen.generate(&pool.projects, start_date, end_date);
4689 }
4690
4691 if self.config.project_accounting.milestones.enabled {
4693 let mut ms_gen = datasynth_generators::project_accounting::MilestoneGenerator::new(
4694 self.config.project_accounting.milestones.clone(),
4695 seed + 97,
4696 );
4697 snapshot.milestones = ms_gen.generate(&pool.projects, start_date, end_date, end_date);
4698 }
4699
4700 if self.config.project_accounting.earned_value.enabled && !snapshot.projects.is_empty() {
4702 let mut evm_gen = datasynth_generators::project_accounting::EarnedValueGenerator::new(
4703 self.config.project_accounting.earned_value.clone(),
4704 seed + 98,
4705 );
4706 snapshot.earned_value_metrics =
4707 evm_gen.generate(&pool.projects, &snapshot.cost_lines, start_date, end_date);
4708 }
4709
4710 stats.project_count = snapshot.projects.len();
4711 stats.project_change_order_count = snapshot.change_orders.len();
4712 stats.project_cost_line_count = snapshot.cost_lines.len();
4713
4714 info!(
4715 "Project accounting generated: {} projects, {} change orders, {} milestones, {} EVM records",
4716 snapshot.projects.len(),
4717 snapshot.change_orders.len(),
4718 snapshot.milestones.len(),
4719 snapshot.earned_value_metrics.len()
4720 );
4721 self.check_resources_with_log("post-project-accounting")?;
4722
4723 Ok(snapshot)
4724 }
4725
4726 fn phase_opening_balances(
4728 &mut self,
4729 coa: &Arc<ChartOfAccounts>,
4730 stats: &mut EnhancedGenerationStatistics,
4731 ) -> SynthResult<Vec<GeneratedOpeningBalance>> {
4732 if !self.config.balance.generate_opening_balances {
4733 debug!("Phase 3b: Skipped (opening balance generation disabled)");
4734 return Ok(Vec::new());
4735 }
4736 info!("Phase 3b: Generating Opening Balances");
4737
4738 let start_date = NaiveDate::parse_from_str(&self.config.global.start_date, "%Y-%m-%d")
4739 .map_err(|e| SynthError::config(format!("Invalid start_date: {}", e)))?;
4740 let fiscal_year = start_date.year();
4741
4742 let industry = match self.config.global.industry {
4743 IndustrySector::Manufacturing => IndustryType::Manufacturing,
4744 IndustrySector::Retail => IndustryType::Retail,
4745 IndustrySector::FinancialServices => IndustryType::Financial,
4746 IndustrySector::Healthcare => IndustryType::Healthcare,
4747 IndustrySector::Technology => IndustryType::Technology,
4748 _ => IndustryType::Manufacturing,
4749 };
4750
4751 let config = datasynth_generators::OpeningBalanceConfig {
4752 industry,
4753 ..Default::default()
4754 };
4755 let mut gen =
4756 datasynth_generators::OpeningBalanceGenerator::with_seed(config, self.seed + 200);
4757
4758 let mut results = Vec::new();
4759 for company in &self.config.companies {
4760 let spec = OpeningBalanceSpec::new(
4761 company.code.clone(),
4762 start_date,
4763 fiscal_year,
4764 company.currency.clone(),
4765 rust_decimal::Decimal::new(10_000_000, 0),
4766 industry,
4767 );
4768 let ob = gen.generate(&spec, coa, start_date, &company.code);
4769 results.push(ob);
4770 }
4771
4772 stats.opening_balance_count = results.len();
4773 info!("Opening balances generated: {} companies", results.len());
4774 self.check_resources_with_log("post-opening-balances")?;
4775
4776 Ok(results)
4777 }
4778
4779 fn phase_subledger_reconciliation(
4781 &mut self,
4782 subledger: &SubledgerSnapshot,
4783 entries: &[JournalEntry],
4784 stats: &mut EnhancedGenerationStatistics,
4785 ) -> SynthResult<Vec<datasynth_generators::ReconciliationResult>> {
4786 if !self.config.balance.reconcile_subledgers {
4787 debug!("Phase 9b: Skipped (subledger reconciliation disabled)");
4788 return Ok(Vec::new());
4789 }
4790 info!("Phase 9b: Reconciling GL to subledger balances");
4791
4792 let end_date = NaiveDate::parse_from_str(&self.config.global.start_date, "%Y-%m-%d")
4793 .map(|d| d + chrono::Months::new(self.config.global.period_months))
4794 .map_err(|e| SynthError::config(format!("Invalid start_date: {}", e)))?;
4795
4796 let tracker_config = BalanceTrackerConfig {
4798 validate_on_each_entry: false,
4799 track_history: false,
4800 fail_on_validation_error: false,
4801 ..Default::default()
4802 };
4803 let recon_currency = self
4804 .config
4805 .companies
4806 .first()
4807 .map(|c| c.currency.clone())
4808 .unwrap_or_else(|| "USD".to_string());
4809 let mut tracker = RunningBalanceTracker::new_with_currency(tracker_config, recon_currency);
4810 let _ = tracker.apply_entries(entries);
4811
4812 let mut engine = datasynth_generators::ReconciliationEngine::new(
4813 datasynth_generators::ReconciliationConfig::default(),
4814 );
4815
4816 let mut results = Vec::new();
4817 let company_code = self
4818 .config
4819 .companies
4820 .first()
4821 .map(|c| c.code.as_str())
4822 .unwrap_or("1000");
4823
4824 if !subledger.ar_invoices.is_empty() {
4826 let gl_balance = tracker
4827 .get_account_balance(
4828 company_code,
4829 datasynth_core::accounts::control_accounts::AR_CONTROL,
4830 )
4831 .map(|b| b.closing_balance)
4832 .unwrap_or_default();
4833 let ar_refs: Vec<&ARInvoice> = subledger.ar_invoices.iter().collect();
4834 results.push(engine.reconcile_ar(company_code, end_date, gl_balance, &ar_refs));
4835 }
4836
4837 if !subledger.ap_invoices.is_empty() {
4839 let gl_balance = tracker
4840 .get_account_balance(
4841 company_code,
4842 datasynth_core::accounts::control_accounts::AP_CONTROL,
4843 )
4844 .map(|b| b.closing_balance)
4845 .unwrap_or_default();
4846 let ap_refs: Vec<&APInvoice> = subledger.ap_invoices.iter().collect();
4847 results.push(engine.reconcile_ap(company_code, end_date, gl_balance, &ap_refs));
4848 }
4849
4850 if !subledger.fa_records.is_empty() {
4852 let gl_asset_balance = tracker
4853 .get_account_balance(
4854 company_code,
4855 datasynth_core::accounts::control_accounts::FIXED_ASSETS,
4856 )
4857 .map(|b| b.closing_balance)
4858 .unwrap_or_default();
4859 let gl_accum_depr_balance = tracker
4860 .get_account_balance(
4861 company_code,
4862 datasynth_core::accounts::control_accounts::ACCUMULATED_DEPRECIATION,
4863 )
4864 .map(|b| b.closing_balance)
4865 .unwrap_or_default();
4866 let fa_refs: Vec<&datasynth_core::models::subledger::fa::FixedAssetRecord> =
4867 subledger.fa_records.iter().collect();
4868 let (asset_recon, depr_recon) = engine.reconcile_fa(
4869 company_code,
4870 end_date,
4871 gl_asset_balance,
4872 gl_accum_depr_balance,
4873 &fa_refs,
4874 );
4875 results.push(asset_recon);
4876 results.push(depr_recon);
4877 }
4878
4879 if !subledger.inventory_positions.is_empty() {
4881 let gl_balance = tracker
4882 .get_account_balance(
4883 company_code,
4884 datasynth_core::accounts::control_accounts::INVENTORY,
4885 )
4886 .map(|b| b.closing_balance)
4887 .unwrap_or_default();
4888 let inv_refs: Vec<&datasynth_core::models::subledger::inventory::InventoryPosition> =
4889 subledger.inventory_positions.iter().collect();
4890 results.push(engine.reconcile_inventory(company_code, end_date, gl_balance, &inv_refs));
4891 }
4892
4893 stats.subledger_reconciliation_count = results.len();
4894 info!(
4895 "Subledger reconciliation complete: {} reconciliations",
4896 results.len()
4897 );
4898 self.check_resources_with_log("post-subledger-reconciliation")?;
4899
4900 Ok(results)
4901 }
4902
4903 fn generate_coa(&mut self) -> SynthResult<Arc<ChartOfAccounts>> {
4905 let pb = self.create_progress_bar(1, "Generating Chart of Accounts");
4906
4907 let mut gen = ChartOfAccountsGenerator::new(
4908 self.config.chart_of_accounts.complexity,
4909 self.config.global.industry,
4910 self.seed,
4911 );
4912
4913 let coa = Arc::new(gen.generate());
4914 self.coa = Some(Arc::clone(&coa));
4915
4916 if let Some(pb) = pb {
4917 pb.finish_with_message("Chart of Accounts complete");
4918 }
4919
4920 Ok(coa)
4921 }
4922
4923 fn generate_master_data(&mut self) -> SynthResult<()> {
4925 let start_date = NaiveDate::parse_from_str(&self.config.global.start_date, "%Y-%m-%d")
4926 .map_err(|e| SynthError::config(format!("Invalid start_date: {}", e)))?;
4927 let end_date = start_date + chrono::Months::new(self.config.global.period_months);
4928
4929 let total = self.config.companies.len() as u64 * 5; let pb = self.create_progress_bar(total, "Generating Master Data");
4931
4932 let pack = self.primary_pack().clone();
4934
4935 for (i, company) in self.config.companies.iter().enumerate() {
4936 let company_seed = self.seed.wrapping_add(i as u64 * 1000);
4937
4938 let mut vendor_gen = VendorGenerator::new(company_seed);
4940 vendor_gen.set_country_pack(pack.clone());
4941 let vendor_pool = vendor_gen.generate_vendor_pool(
4942 self.phase_config.vendors_per_company,
4943 &company.code,
4944 start_date,
4945 );
4946 self.master_data.vendors.extend(vendor_pool.vendors);
4947 if let Some(pb) = &pb {
4948 pb.inc(1);
4949 }
4950
4951 let mut customer_gen = CustomerGenerator::new(company_seed + 100);
4953 customer_gen.set_country_pack(pack.clone());
4954 let customer_pool = customer_gen.generate_customer_pool(
4955 self.phase_config.customers_per_company,
4956 &company.code,
4957 start_date,
4958 );
4959 self.master_data.customers.extend(customer_pool.customers);
4960 if let Some(pb) = &pb {
4961 pb.inc(1);
4962 }
4963
4964 let mut material_gen = MaterialGenerator::new(company_seed + 200);
4966 material_gen.set_country_pack(pack.clone());
4967 let material_pool = material_gen.generate_material_pool(
4968 self.phase_config.materials_per_company,
4969 &company.code,
4970 start_date,
4971 );
4972 self.master_data.materials.extend(material_pool.materials);
4973 if let Some(pb) = &pb {
4974 pb.inc(1);
4975 }
4976
4977 let mut asset_gen = AssetGenerator::new(company_seed + 300);
4979 let asset_pool = asset_gen.generate_asset_pool(
4980 self.phase_config.assets_per_company,
4981 &company.code,
4982 (start_date, end_date),
4983 );
4984 self.master_data.assets.extend(asset_pool.assets);
4985 if let Some(pb) = &pb {
4986 pb.inc(1);
4987 }
4988
4989 let mut employee_gen = EmployeeGenerator::new(company_seed + 400);
4991 let employee_pool =
4992 employee_gen.generate_company_pool(&company.code, (start_date, end_date));
4993 self.master_data.employees.extend(employee_pool.employees);
4994 if let Some(pb) = &pb {
4995 pb.inc(1);
4996 }
4997 }
4998
4999 if let Some(pb) = pb {
5000 pb.finish_with_message("Master data generation complete");
5001 }
5002
5003 Ok(())
5004 }
5005
5006 fn generate_document_flows(&mut self, flows: &mut DocumentFlowSnapshot) -> SynthResult<()> {
5008 let start_date = NaiveDate::parse_from_str(&self.config.global.start_date, "%Y-%m-%d")
5009 .map_err(|e| SynthError::config(format!("Invalid start_date: {}", e)))?;
5010
5011 let p2p_count = self
5013 .phase_config
5014 .p2p_chains
5015 .min(self.master_data.vendors.len() * 2);
5016 let pb = self.create_progress_bar(p2p_count as u64, "Generating P2P Document Flows");
5017
5018 let p2p_config = convert_p2p_config(&self.config.document_flows.p2p);
5020 let mut p2p_gen = P2PGenerator::with_config(self.seed + 1000, p2p_config);
5021 p2p_gen.set_country_pack(self.primary_pack().clone());
5022
5023 for i in 0..p2p_count {
5024 let vendor = &self.master_data.vendors[i % self.master_data.vendors.len()];
5025 let materials: Vec<&Material> = self
5026 .master_data
5027 .materials
5028 .iter()
5029 .skip(i % self.master_data.materials.len().max(1))
5030 .take(2.min(self.master_data.materials.len()))
5031 .collect();
5032
5033 if materials.is_empty() {
5034 continue;
5035 }
5036
5037 let company = &self.config.companies[i % self.config.companies.len()];
5038 let po_date = start_date + chrono::Duration::days((i * 3) as i64 % 365);
5039 let fiscal_period = po_date.month() as u8;
5040 let created_by = if self.master_data.employees.is_empty() {
5041 "SYSTEM"
5042 } else {
5043 self.master_data.employees[i % self.master_data.employees.len()]
5044 .user_id
5045 .as_str()
5046 };
5047
5048 let chain = p2p_gen.generate_chain(
5049 &company.code,
5050 vendor,
5051 &materials,
5052 po_date,
5053 start_date.year() as u16,
5054 fiscal_period,
5055 created_by,
5056 );
5057
5058 flows.purchase_orders.push(chain.purchase_order.clone());
5060 flows.goods_receipts.extend(chain.goods_receipts.clone());
5061 if let Some(vi) = &chain.vendor_invoice {
5062 flows.vendor_invoices.push(vi.clone());
5063 }
5064 if let Some(payment) = &chain.payment {
5065 flows.payments.push(payment.clone());
5066 }
5067 flows.p2p_chains.push(chain);
5068
5069 if let Some(pb) = &pb {
5070 pb.inc(1);
5071 }
5072 }
5073
5074 if let Some(pb) = pb {
5075 pb.finish_with_message("P2P document flows complete");
5076 }
5077
5078 let o2c_count = self
5080 .phase_config
5081 .o2c_chains
5082 .min(self.master_data.customers.len() * 2);
5083 let pb = self.create_progress_bar(o2c_count as u64, "Generating O2C Document Flows");
5084
5085 let o2c_config = convert_o2c_config(&self.config.document_flows.o2c);
5087 let mut o2c_gen = O2CGenerator::with_config(self.seed + 2000, o2c_config);
5088 o2c_gen.set_country_pack(self.primary_pack().clone());
5089
5090 for i in 0..o2c_count {
5091 let customer = &self.master_data.customers[i % self.master_data.customers.len()];
5092 let materials: Vec<&Material> = self
5093 .master_data
5094 .materials
5095 .iter()
5096 .skip(i % self.master_data.materials.len().max(1))
5097 .take(2.min(self.master_data.materials.len()))
5098 .collect();
5099
5100 if materials.is_empty() {
5101 continue;
5102 }
5103
5104 let company = &self.config.companies[i % self.config.companies.len()];
5105 let so_date = start_date + chrono::Duration::days((i * 2) as i64 % 365);
5106 let fiscal_period = so_date.month() as u8;
5107 let created_by = if self.master_data.employees.is_empty() {
5108 "SYSTEM"
5109 } else {
5110 self.master_data.employees[i % self.master_data.employees.len()]
5111 .user_id
5112 .as_str()
5113 };
5114
5115 let chain = o2c_gen.generate_chain(
5116 &company.code,
5117 customer,
5118 &materials,
5119 so_date,
5120 start_date.year() as u16,
5121 fiscal_period,
5122 created_by,
5123 );
5124
5125 flows.sales_orders.push(chain.sales_order.clone());
5127 flows.deliveries.extend(chain.deliveries.clone());
5128 if let Some(ci) = &chain.customer_invoice {
5129 flows.customer_invoices.push(ci.clone());
5130 }
5131 if let Some(receipt) = &chain.customer_receipt {
5132 flows.payments.push(receipt.clone());
5133 }
5134 flows.o2c_chains.push(chain);
5135
5136 if let Some(pb) = &pb {
5137 pb.inc(1);
5138 }
5139 }
5140
5141 if let Some(pb) = pb {
5142 pb.finish_with_message("O2C document flows complete");
5143 }
5144
5145 Ok(())
5146 }
5147
5148 fn generate_journal_entries(
5150 &mut self,
5151 coa: &Arc<ChartOfAccounts>,
5152 ) -> SynthResult<Vec<JournalEntry>> {
5153 let total = self.calculate_total_transactions();
5154 let pb = self.create_progress_bar(total, "Generating Journal Entries");
5155
5156 let start_date = NaiveDate::parse_from_str(&self.config.global.start_date, "%Y-%m-%d")
5157 .map_err(|e| SynthError::config(format!("Invalid start_date: {}", e)))?;
5158 let end_date = start_date + chrono::Months::new(self.config.global.period_months);
5159
5160 let company_codes: Vec<String> = self
5161 .config
5162 .companies
5163 .iter()
5164 .map(|c| c.code.clone())
5165 .collect();
5166
5167 let generator = JournalEntryGenerator::new_with_params(
5168 self.config.transactions.clone(),
5169 Arc::clone(coa),
5170 company_codes,
5171 start_date,
5172 end_date,
5173 self.seed,
5174 );
5175
5176 let je_pack = self.primary_pack();
5180
5181 let mut generator = generator
5182 .with_master_data(
5183 &self.master_data.vendors,
5184 &self.master_data.customers,
5185 &self.master_data.materials,
5186 )
5187 .with_country_pack_names(je_pack)
5188 .with_country_pack_temporal(
5189 self.config.temporal_patterns.clone(),
5190 self.seed + 200,
5191 je_pack,
5192 )
5193 .with_persona_errors(true)
5194 .with_fraud_config(self.config.fraud.clone());
5195
5196 if self.config.temporal.enabled {
5198 let drift_config = self.config.temporal.to_core_config();
5199 generator = generator.with_drift_config(drift_config, self.seed + 100);
5200 }
5201
5202 let mut entries = Vec::with_capacity(total as usize);
5203
5204 self.check_memory_limit()?;
5206
5207 const MEMORY_CHECK_INTERVAL: u64 = 1000;
5209
5210 for i in 0..total {
5211 let entry = generator.generate();
5212 entries.push(entry);
5213 if let Some(pb) = &pb {
5214 pb.inc(1);
5215 }
5216
5217 if (i + 1) % MEMORY_CHECK_INTERVAL == 0 {
5219 self.check_memory_limit()?;
5220 }
5221 }
5222
5223 if let Some(pb) = pb {
5224 pb.finish_with_message("Journal entries complete");
5225 }
5226
5227 Ok(entries)
5228 }
5229
5230 fn generate_jes_from_document_flows(
5235 &mut self,
5236 flows: &DocumentFlowSnapshot,
5237 ) -> SynthResult<Vec<JournalEntry>> {
5238 let total_chains = flows.p2p_chains.len() + flows.o2c_chains.len();
5239 let pb = self.create_progress_bar(total_chains as u64, "Generating Document Flow JEs");
5240
5241 let mut generator = DocumentFlowJeGenerator::with_config_and_seed(
5242 DocumentFlowJeConfig::default(),
5243 self.seed,
5244 );
5245 let mut entries = Vec::new();
5246
5247 for chain in &flows.p2p_chains {
5249 let chain_entries = generator.generate_from_p2p_chain(chain);
5250 entries.extend(chain_entries);
5251 if let Some(pb) = &pb {
5252 pb.inc(1);
5253 }
5254 }
5255
5256 for chain in &flows.o2c_chains {
5258 let chain_entries = generator.generate_from_o2c_chain(chain);
5259 entries.extend(chain_entries);
5260 if let Some(pb) = &pb {
5261 pb.inc(1);
5262 }
5263 }
5264
5265 if let Some(pb) = pb {
5266 pb.finish_with_message(format!(
5267 "Generated {} JEs from document flows",
5268 entries.len()
5269 ));
5270 }
5271
5272 Ok(entries)
5273 }
5274
5275 fn generate_payroll_jes(payroll_runs: &[PayrollRun]) -> Vec<JournalEntry> {
5281 use datasynth_core::accounts::{expense_accounts, suspense_accounts};
5282
5283 let mut jes = Vec::with_capacity(payroll_runs.len());
5284
5285 for run in payroll_runs {
5286 let mut je = JournalEntry::new_simple(
5287 format!("JE-PAYROLL-{}", run.payroll_id),
5288 run.company_code.clone(),
5289 run.run_date,
5290 format!("Payroll {}", run.payroll_id),
5291 );
5292
5293 je.add_line(JournalEntryLine {
5295 line_number: 1,
5296 gl_account: expense_accounts::SALARIES_WAGES.to_string(),
5297 debit_amount: run.total_gross,
5298 reference: Some(run.payroll_id.clone()),
5299 text: Some(format!(
5300 "Payroll {} ({} employees)",
5301 run.payroll_id, run.employee_count
5302 )),
5303 ..Default::default()
5304 });
5305
5306 je.add_line(JournalEntryLine {
5308 line_number: 2,
5309 gl_account: suspense_accounts::PAYROLL_CLEARING.to_string(),
5310 credit_amount: run.total_gross,
5311 reference: Some(run.payroll_id.clone()),
5312 ..Default::default()
5313 });
5314
5315 jes.push(je);
5316 }
5317
5318 jes
5319 }
5320
5321 fn generate_manufacturing_jes(production_orders: &[ProductionOrder]) -> Vec<JournalEntry> {
5327 use datasynth_core::accounts::{control_accounts, expense_accounts};
5328 use datasynth_core::models::ProductionOrderStatus;
5329
5330 let mut jes = Vec::new();
5331
5332 for order in production_orders {
5333 if !matches!(
5335 order.status,
5336 ProductionOrderStatus::Completed | ProductionOrderStatus::Closed
5337 ) {
5338 continue;
5339 }
5340
5341 let mut je = JournalEntry::new_simple(
5342 format!("JE-MFG-{}", order.order_id),
5343 order.company_code.clone(),
5344 order.actual_end.unwrap_or(order.planned_end),
5345 format!(
5346 "Production Order {} - {}",
5347 order.order_id, order.material_description
5348 ),
5349 );
5350
5351 je.add_line(JournalEntryLine {
5353 line_number: 1,
5354 gl_account: expense_accounts::RAW_MATERIALS.to_string(),
5355 debit_amount: order.actual_cost,
5356 reference: Some(order.order_id.clone()),
5357 text: Some(format!(
5358 "Material consumption for {}",
5359 order.material_description
5360 )),
5361 quantity: Some(order.actual_quantity),
5362 unit: Some("EA".to_string()),
5363 ..Default::default()
5364 });
5365
5366 je.add_line(JournalEntryLine {
5368 line_number: 2,
5369 gl_account: control_accounts::INVENTORY.to_string(),
5370 credit_amount: order.actual_cost,
5371 reference: Some(order.order_id.clone()),
5372 ..Default::default()
5373 });
5374
5375 jes.push(je);
5376 }
5377
5378 jes
5379 }
5380
5381 fn link_document_flows_to_subledgers(
5386 &mut self,
5387 flows: &DocumentFlowSnapshot,
5388 ) -> SynthResult<SubledgerSnapshot> {
5389 let total = flows.vendor_invoices.len() + flows.customer_invoices.len();
5390 let pb = self.create_progress_bar(total as u64, "Linking Subledgers");
5391
5392 let vendor_names: std::collections::HashMap<String, String> = self
5394 .master_data
5395 .vendors
5396 .iter()
5397 .map(|v| (v.vendor_id.clone(), v.name.clone()))
5398 .collect();
5399 let customer_names: std::collections::HashMap<String, String> = self
5400 .master_data
5401 .customers
5402 .iter()
5403 .map(|c| (c.customer_id.clone(), c.name.clone()))
5404 .collect();
5405
5406 let mut linker = DocumentFlowLinker::new()
5407 .with_vendor_names(vendor_names)
5408 .with_customer_names(customer_names);
5409
5410 let ap_invoices = linker.batch_create_ap_invoices(&flows.vendor_invoices);
5412 if let Some(pb) = &pb {
5413 pb.inc(flows.vendor_invoices.len() as u64);
5414 }
5415
5416 let ar_invoices = linker.batch_create_ar_invoices(&flows.customer_invoices);
5418 if let Some(pb) = &pb {
5419 pb.inc(flows.customer_invoices.len() as u64);
5420 }
5421
5422 if let Some(pb) = pb {
5423 pb.finish_with_message(format!(
5424 "Linked {} AP and {} AR invoices",
5425 ap_invoices.len(),
5426 ar_invoices.len()
5427 ));
5428 }
5429
5430 Ok(SubledgerSnapshot {
5431 ap_invoices,
5432 ar_invoices,
5433 fa_records: Vec::new(),
5434 inventory_positions: Vec::new(),
5435 inventory_movements: Vec::new(),
5436 })
5437 }
5438
5439 #[allow(clippy::too_many_arguments)]
5444 fn generate_ocpm_events(
5445 &mut self,
5446 flows: &DocumentFlowSnapshot,
5447 sourcing: &SourcingSnapshot,
5448 hr: &HrSnapshot,
5449 manufacturing: &ManufacturingSnapshot,
5450 banking: &BankingSnapshot,
5451 audit: &AuditSnapshot,
5452 financial_reporting: &FinancialReportingSnapshot,
5453 ) -> SynthResult<OcpmSnapshot> {
5454 let total_chains = flows.p2p_chains.len()
5455 + flows.o2c_chains.len()
5456 + sourcing.sourcing_projects.len()
5457 + hr.payroll_runs.len()
5458 + manufacturing.production_orders.len()
5459 + banking.customers.len()
5460 + audit.engagements.len()
5461 + financial_reporting.bank_reconciliations.len();
5462 let pb = self.create_progress_bar(total_chains as u64, "Generating OCPM Events");
5463
5464 let metadata = EventLogMetadata::new("SyntheticData OCPM Log");
5466 let mut event_log = OcpmEventLog::with_metadata(metadata).with_standard_types();
5467
5468 let ocpm_config = OcpmGeneratorConfig {
5470 generate_p2p: true,
5471 generate_o2c: true,
5472 generate_s2c: !sourcing.sourcing_projects.is_empty(),
5473 generate_h2r: !hr.payroll_runs.is_empty(),
5474 generate_mfg: !manufacturing.production_orders.is_empty(),
5475 generate_bank_recon: !financial_reporting.bank_reconciliations.is_empty(),
5476 generate_bank: !banking.customers.is_empty(),
5477 generate_audit: !audit.engagements.is_empty(),
5478 happy_path_rate: 0.75,
5479 exception_path_rate: 0.20,
5480 error_path_rate: 0.05,
5481 add_duration_variability: true,
5482 duration_std_dev_factor: 0.3,
5483 };
5484 let mut ocpm_gen = OcpmEventGenerator::with_config(self.seed + 3000, ocpm_config);
5485 let ocpm_uuid_factory = OcpmUuidFactory::new(self.seed + 3001);
5486
5487 let available_users: Vec<String> = self
5489 .master_data
5490 .employees
5491 .iter()
5492 .take(20)
5493 .map(|e| e.user_id.clone())
5494 .collect();
5495
5496 let fallback_date =
5498 NaiveDate::from_ymd_opt(2024, 1, 1).expect("static date 2024-01-01 is always valid");
5499 let base_date = NaiveDate::parse_from_str(&self.config.global.start_date, "%Y-%m-%d")
5500 .unwrap_or(fallback_date);
5501 let base_midnight = base_date
5502 .and_hms_opt(0, 0, 0)
5503 .expect("midnight is always valid");
5504 let base_datetime =
5505 chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(base_midnight, chrono::Utc);
5506
5507 let add_result = |event_log: &mut OcpmEventLog,
5509 result: datasynth_ocpm::CaseGenerationResult| {
5510 for event in result.events {
5511 event_log.add_event(event);
5512 }
5513 for object in result.objects {
5514 event_log.add_object(object);
5515 }
5516 for relationship in result.relationships {
5517 event_log.add_relationship(relationship);
5518 }
5519 event_log.add_case(result.case_trace);
5520 };
5521
5522 for chain in &flows.p2p_chains {
5524 let po = &chain.purchase_order;
5525 let documents = P2pDocuments::new(
5526 &po.header.document_id,
5527 &po.vendor_id,
5528 &po.header.company_code,
5529 po.total_net_amount,
5530 &po.header.currency,
5531 &ocpm_uuid_factory,
5532 )
5533 .with_goods_receipt(
5534 chain
5535 .goods_receipts
5536 .first()
5537 .map(|gr| gr.header.document_id.as_str())
5538 .unwrap_or(""),
5539 &ocpm_uuid_factory,
5540 )
5541 .with_invoice(
5542 chain
5543 .vendor_invoice
5544 .as_ref()
5545 .map(|vi| vi.header.document_id.as_str())
5546 .unwrap_or(""),
5547 &ocpm_uuid_factory,
5548 )
5549 .with_payment(
5550 chain
5551 .payment
5552 .as_ref()
5553 .map(|p| p.header.document_id.as_str())
5554 .unwrap_or(""),
5555 &ocpm_uuid_factory,
5556 );
5557
5558 let start_time =
5559 chrono::DateTime::from_naive_utc_and_offset(po.header.entry_timestamp, chrono::Utc);
5560 let result = ocpm_gen.generate_p2p_case(&documents, start_time, &available_users);
5561 add_result(&mut event_log, result);
5562
5563 if let Some(pb) = &pb {
5564 pb.inc(1);
5565 }
5566 }
5567
5568 for chain in &flows.o2c_chains {
5570 let so = &chain.sales_order;
5571 let documents = O2cDocuments::new(
5572 &so.header.document_id,
5573 &so.customer_id,
5574 &so.header.company_code,
5575 so.total_net_amount,
5576 &so.header.currency,
5577 &ocpm_uuid_factory,
5578 )
5579 .with_delivery(
5580 chain
5581 .deliveries
5582 .first()
5583 .map(|d| d.header.document_id.as_str())
5584 .unwrap_or(""),
5585 &ocpm_uuid_factory,
5586 )
5587 .with_invoice(
5588 chain
5589 .customer_invoice
5590 .as_ref()
5591 .map(|ci| ci.header.document_id.as_str())
5592 .unwrap_or(""),
5593 &ocpm_uuid_factory,
5594 )
5595 .with_receipt(
5596 chain
5597 .customer_receipt
5598 .as_ref()
5599 .map(|r| r.header.document_id.as_str())
5600 .unwrap_or(""),
5601 &ocpm_uuid_factory,
5602 );
5603
5604 let start_time =
5605 chrono::DateTime::from_naive_utc_and_offset(so.header.entry_timestamp, chrono::Utc);
5606 let result = ocpm_gen.generate_o2c_case(&documents, start_time, &available_users);
5607 add_result(&mut event_log, result);
5608
5609 if let Some(pb) = &pb {
5610 pb.inc(1);
5611 }
5612 }
5613
5614 for project in &sourcing.sourcing_projects {
5616 let vendor_id = sourcing
5618 .contracts
5619 .iter()
5620 .find(|c| c.sourcing_project_id.as_deref() == Some(&project.project_id))
5621 .map(|c| c.vendor_id.clone())
5622 .or_else(|| sourcing.qualifications.first().map(|q| q.vendor_id.clone()))
5623 .or_else(|| {
5624 self.master_data
5625 .vendors
5626 .first()
5627 .map(|v| v.vendor_id.clone())
5628 })
5629 .unwrap_or_else(|| "V000".to_string());
5630 let mut docs = S2cDocuments::new(
5631 &project.project_id,
5632 &vendor_id,
5633 &project.company_code,
5634 project.estimated_annual_spend,
5635 &ocpm_uuid_factory,
5636 );
5637 if let Some(rfx) = sourcing
5639 .rfx_events
5640 .iter()
5641 .find(|r| r.sourcing_project_id == project.project_id)
5642 {
5643 docs = docs.with_rfx(&rfx.rfx_id, &ocpm_uuid_factory);
5644 if let Some(bid) = sourcing.bids.iter().find(|b| {
5646 b.rfx_id == rfx.rfx_id
5647 && b.status == datasynth_core::models::sourcing::BidStatus::Accepted
5648 }) {
5649 docs = docs.with_winning_bid(&bid.bid_id, &ocpm_uuid_factory);
5650 }
5651 }
5652 if let Some(contract) = sourcing
5654 .contracts
5655 .iter()
5656 .find(|c| c.sourcing_project_id.as_deref() == Some(&project.project_id))
5657 {
5658 docs = docs.with_contract(&contract.contract_id, &ocpm_uuid_factory);
5659 }
5660 let start_time = base_datetime - chrono::Duration::days(90);
5661 let result = ocpm_gen.generate_s2c_case(&docs, start_time, &available_users);
5662 add_result(&mut event_log, result);
5663
5664 if let Some(pb) = &pb {
5665 pb.inc(1);
5666 }
5667 }
5668
5669 for run in &hr.payroll_runs {
5671 let employee_id = hr
5673 .payroll_line_items
5674 .iter()
5675 .find(|li| li.payroll_id == run.payroll_id)
5676 .map(|li| li.employee_id.as_str())
5677 .unwrap_or("EMP000");
5678 let docs = H2rDocuments::new(
5679 &run.payroll_id,
5680 employee_id,
5681 &run.company_code,
5682 run.total_gross,
5683 &ocpm_uuid_factory,
5684 )
5685 .with_time_entries(
5686 hr.time_entries
5687 .iter()
5688 .filter(|t| t.date >= run.pay_period_start && t.date <= run.pay_period_end)
5689 .take(5)
5690 .map(|t| t.entry_id.as_str())
5691 .collect(),
5692 );
5693 let start_time = base_datetime - chrono::Duration::days(30);
5694 let result = ocpm_gen.generate_h2r_case(&docs, start_time, &available_users);
5695 add_result(&mut event_log, result);
5696
5697 if let Some(pb) = &pb {
5698 pb.inc(1);
5699 }
5700 }
5701
5702 for order in &manufacturing.production_orders {
5704 let mut docs = MfgDocuments::new(
5705 &order.order_id,
5706 &order.material_id,
5707 &order.company_code,
5708 order.planned_quantity,
5709 &ocpm_uuid_factory,
5710 )
5711 .with_operations(
5712 order
5713 .operations
5714 .iter()
5715 .map(|o| format!("OP-{:04}", o.operation_number))
5716 .collect::<Vec<_>>()
5717 .iter()
5718 .map(|s| s.as_str())
5719 .collect(),
5720 );
5721 if let Some(insp) = manufacturing
5723 .quality_inspections
5724 .iter()
5725 .find(|i| i.reference_id == order.order_id)
5726 {
5727 docs = docs.with_inspection(&insp.inspection_id, &ocpm_uuid_factory);
5728 }
5729 if let Some(cc) = manufacturing.cycle_counts.iter().find(|cc| {
5731 cc.items
5732 .iter()
5733 .any(|item| item.material_id == order.material_id)
5734 }) {
5735 docs = docs.with_cycle_count(&cc.count_id, &ocpm_uuid_factory);
5736 }
5737 let start_time = base_datetime - chrono::Duration::days(60);
5738 let result = ocpm_gen.generate_mfg_case(&docs, start_time, &available_users);
5739 add_result(&mut event_log, result);
5740
5741 if let Some(pb) = &pb {
5742 pb.inc(1);
5743 }
5744 }
5745
5746 for customer in &banking.customers {
5748 let customer_id_str = customer.customer_id.to_string();
5749 let mut docs = BankDocuments::new(&customer_id_str, "1000", &ocpm_uuid_factory);
5750 if let Some(account) = banking
5752 .accounts
5753 .iter()
5754 .find(|a| a.primary_owner_id == customer.customer_id)
5755 {
5756 let account_id_str = account.account_id.to_string();
5757 docs = docs.with_account(&account_id_str, &ocpm_uuid_factory);
5758 let txn_strs: Vec<String> = banking
5760 .transactions
5761 .iter()
5762 .filter(|t| t.account_id == account.account_id)
5763 .take(10)
5764 .map(|t| t.transaction_id.to_string())
5765 .collect();
5766 let txn_ids: Vec<&str> = txn_strs.iter().map(|s| s.as_str()).collect();
5767 let txn_amounts: Vec<rust_decimal::Decimal> = banking
5768 .transactions
5769 .iter()
5770 .filter(|t| t.account_id == account.account_id)
5771 .take(10)
5772 .map(|t| t.amount)
5773 .collect();
5774 if !txn_ids.is_empty() {
5775 docs = docs.with_transactions(txn_ids, txn_amounts);
5776 }
5777 }
5778 let start_time = base_datetime - chrono::Duration::days(180);
5779 let result = ocpm_gen.generate_bank_case(&docs, start_time, &available_users);
5780 add_result(&mut event_log, result);
5781
5782 if let Some(pb) = &pb {
5783 pb.inc(1);
5784 }
5785 }
5786
5787 for engagement in &audit.engagements {
5789 let engagement_id_str = engagement.engagement_id.to_string();
5790 let docs = AuditDocuments::new(
5791 &engagement_id_str,
5792 &engagement.client_entity_id,
5793 &ocpm_uuid_factory,
5794 )
5795 .with_workpapers(
5796 audit
5797 .workpapers
5798 .iter()
5799 .filter(|w| w.engagement_id == engagement.engagement_id)
5800 .take(10)
5801 .map(|w| w.workpaper_id.to_string())
5802 .collect::<Vec<_>>()
5803 .iter()
5804 .map(|s| s.as_str())
5805 .collect(),
5806 )
5807 .with_evidence(
5808 audit
5809 .evidence
5810 .iter()
5811 .filter(|e| e.engagement_id == engagement.engagement_id)
5812 .take(10)
5813 .map(|e| e.evidence_id.to_string())
5814 .collect::<Vec<_>>()
5815 .iter()
5816 .map(|s| s.as_str())
5817 .collect(),
5818 )
5819 .with_risks(
5820 audit
5821 .risk_assessments
5822 .iter()
5823 .filter(|r| r.engagement_id == engagement.engagement_id)
5824 .take(5)
5825 .map(|r| r.risk_id.to_string())
5826 .collect::<Vec<_>>()
5827 .iter()
5828 .map(|s| s.as_str())
5829 .collect(),
5830 )
5831 .with_findings(
5832 audit
5833 .findings
5834 .iter()
5835 .filter(|f| f.engagement_id == engagement.engagement_id)
5836 .take(5)
5837 .map(|f| f.finding_id.to_string())
5838 .collect::<Vec<_>>()
5839 .iter()
5840 .map(|s| s.as_str())
5841 .collect(),
5842 )
5843 .with_judgments(
5844 audit
5845 .judgments
5846 .iter()
5847 .filter(|j| j.engagement_id == engagement.engagement_id)
5848 .take(5)
5849 .map(|j| j.judgment_id.to_string())
5850 .collect::<Vec<_>>()
5851 .iter()
5852 .map(|s| s.as_str())
5853 .collect(),
5854 );
5855 let start_time = base_datetime - chrono::Duration::days(120);
5856 let result = ocpm_gen.generate_audit_case(&docs, start_time, &available_users);
5857 add_result(&mut event_log, result);
5858
5859 if let Some(pb) = &pb {
5860 pb.inc(1);
5861 }
5862 }
5863
5864 for recon in &financial_reporting.bank_reconciliations {
5866 let docs = BankReconDocuments::new(
5867 &recon.reconciliation_id,
5868 &recon.bank_account_id,
5869 &recon.company_code,
5870 recon.bank_ending_balance,
5871 &ocpm_uuid_factory,
5872 )
5873 .with_statement_lines(
5874 recon
5875 .statement_lines
5876 .iter()
5877 .take(20)
5878 .map(|l| l.line_id.as_str())
5879 .collect(),
5880 )
5881 .with_reconciling_items(
5882 recon
5883 .reconciling_items
5884 .iter()
5885 .take(10)
5886 .map(|i| i.item_id.as_str())
5887 .collect(),
5888 );
5889 let start_time = base_datetime - chrono::Duration::days(30);
5890 let result = ocpm_gen.generate_bank_recon_case(&docs, start_time, &available_users);
5891 add_result(&mut event_log, result);
5892
5893 if let Some(pb) = &pb {
5894 pb.inc(1);
5895 }
5896 }
5897
5898 event_log.compute_variants();
5900
5901 let summary = event_log.summary();
5902
5903 if let Some(pb) = pb {
5904 pb.finish_with_message(format!(
5905 "Generated {} OCPM events, {} objects",
5906 summary.event_count, summary.object_count
5907 ));
5908 }
5909
5910 Ok(OcpmSnapshot {
5911 event_count: summary.event_count,
5912 object_count: summary.object_count,
5913 case_count: summary.case_count,
5914 event_log: Some(event_log),
5915 })
5916 }
5917
5918 fn inject_anomalies(&mut self, entries: &mut [JournalEntry]) -> SynthResult<AnomalyLabels> {
5920 let pb = self.create_progress_bar(entries.len() as u64, "Injecting Anomalies");
5921
5922 let total_rate = if self.config.anomaly_injection.enabled {
5925 self.config.anomaly_injection.rates.total_rate
5926 } else if self.config.fraud.enabled {
5927 self.config.fraud.fraud_rate
5928 } else {
5929 0.02
5930 };
5931
5932 let fraud_rate = if self.config.anomaly_injection.enabled {
5933 self.config.anomaly_injection.rates.fraud_rate
5934 } else {
5935 AnomalyRateConfig::default().fraud_rate
5936 };
5937
5938 let error_rate = if self.config.anomaly_injection.enabled {
5939 self.config.anomaly_injection.rates.error_rate
5940 } else {
5941 AnomalyRateConfig::default().error_rate
5942 };
5943
5944 let process_issue_rate = if self.config.anomaly_injection.enabled {
5945 self.config.anomaly_injection.rates.process_rate
5946 } else {
5947 AnomalyRateConfig::default().process_issue_rate
5948 };
5949
5950 let anomaly_config = AnomalyInjectorConfig {
5951 rates: AnomalyRateConfig {
5952 total_rate,
5953 fraud_rate,
5954 error_rate,
5955 process_issue_rate,
5956 ..Default::default()
5957 },
5958 seed: self.seed + 5000,
5959 ..Default::default()
5960 };
5961
5962 let mut injector = AnomalyInjector::new(anomaly_config);
5963 let result = injector.process_entries(entries);
5964
5965 if let Some(pb) = &pb {
5966 pb.inc(entries.len() as u64);
5967 pb.finish_with_message("Anomaly injection complete");
5968 }
5969
5970 let mut by_type = HashMap::new();
5971 for label in &result.labels {
5972 *by_type
5973 .entry(format!("{:?}", label.anomaly_type))
5974 .or_insert(0) += 1;
5975 }
5976
5977 Ok(AnomalyLabels {
5978 labels: result.labels,
5979 summary: Some(result.summary),
5980 by_type,
5981 })
5982 }
5983
5984 fn validate_journal_entries(
5993 &mut self,
5994 entries: &[JournalEntry],
5995 ) -> SynthResult<BalanceValidationResult> {
5996 let clean_entries: Vec<&JournalEntry> = entries
5998 .iter()
5999 .filter(|e| {
6000 e.header
6001 .header_text
6002 .as_ref()
6003 .map(|t| !t.contains("[HUMAN_ERROR:"))
6004 .unwrap_or(true)
6005 })
6006 .collect();
6007
6008 let pb = self.create_progress_bar(clean_entries.len() as u64, "Validating Balances");
6009
6010 let config = BalanceTrackerConfig {
6012 validate_on_each_entry: false, track_history: false, fail_on_validation_error: false, ..Default::default()
6016 };
6017 let validation_currency = self
6018 .config
6019 .companies
6020 .first()
6021 .map(|c| c.currency.clone())
6022 .unwrap_or_else(|| "USD".to_string());
6023
6024 let mut tracker = RunningBalanceTracker::new_with_currency(config, validation_currency);
6025
6026 let clean_refs: Vec<JournalEntry> = clean_entries.into_iter().cloned().collect();
6028 let errors = tracker.apply_entries(&clean_refs);
6029
6030 if let Some(pb) = &pb {
6031 pb.inc(entries.len() as u64);
6032 }
6033
6034 let has_unbalanced = tracker
6037 .get_validation_errors()
6038 .iter()
6039 .any(|e| e.error_type == datasynth_generators::ValidationErrorType::UnbalancedEntry);
6040
6041 let mut all_errors = errors;
6044 all_errors.extend(tracker.get_validation_errors().iter().cloned());
6045 let company_codes: Vec<String> = self
6046 .config
6047 .companies
6048 .iter()
6049 .map(|c| c.code.clone())
6050 .collect();
6051
6052 let end_date = NaiveDate::parse_from_str(&self.config.global.start_date, "%Y-%m-%d")
6053 .map(|d| d + chrono::Months::new(self.config.global.period_months))
6054 .map_err(|e| SynthError::config(format!("Invalid start_date: {}", e)))?;
6055
6056 for company_code in &company_codes {
6057 if let Err(e) = tracker.validate_balance_sheet(company_code, end_date, None) {
6058 all_errors.push(e);
6059 }
6060 }
6061
6062 let stats = tracker.get_statistics();
6064
6065 let is_balanced = all_errors.is_empty();
6067
6068 if let Some(pb) = pb {
6069 let msg = if is_balanced {
6070 "Balance validation passed"
6071 } else {
6072 "Balance validation completed with errors"
6073 };
6074 pb.finish_with_message(msg);
6075 }
6076
6077 Ok(BalanceValidationResult {
6078 validated: true,
6079 is_balanced,
6080 entries_processed: stats.entries_processed,
6081 total_debits: stats.total_debits,
6082 total_credits: stats.total_credits,
6083 accounts_tracked: stats.accounts_tracked,
6084 companies_tracked: stats.companies_tracked,
6085 validation_errors: all_errors,
6086 has_unbalanced_entries: has_unbalanced,
6087 })
6088 }
6089
6090 fn inject_data_quality(
6095 &mut self,
6096 entries: &mut [JournalEntry],
6097 ) -> SynthResult<DataQualityStats> {
6098 let pb = self.create_progress_bar(entries.len() as u64, "Injecting Data Quality Issues");
6099
6100 let config = if self.config.data_quality.enabled {
6103 let dq = &self.config.data_quality;
6104 DataQualityConfig {
6105 enable_missing_values: dq.missing_values.enabled,
6106 missing_values: datasynth_generators::MissingValueConfig {
6107 global_rate: dq.effective_missing_rate(),
6108 ..Default::default()
6109 },
6110 enable_format_variations: dq.format_variations.enabled,
6111 format_variations: datasynth_generators::FormatVariationConfig {
6112 date_variation_rate: dq.format_variations.dates.rate,
6113 amount_variation_rate: dq.format_variations.amounts.rate,
6114 identifier_variation_rate: dq.format_variations.identifiers.rate,
6115 ..Default::default()
6116 },
6117 enable_duplicates: dq.duplicates.enabled,
6118 duplicates: datasynth_generators::DuplicateConfig {
6119 duplicate_rate: dq.effective_duplicate_rate(),
6120 ..Default::default()
6121 },
6122 enable_typos: dq.typos.enabled,
6123 typos: datasynth_generators::TypoConfig {
6124 char_error_rate: dq.effective_typo_rate(),
6125 ..Default::default()
6126 },
6127 enable_encoding_issues: dq.encoding_issues.enabled,
6128 encoding_issue_rate: dq.encoding_issues.rate,
6129 seed: self.seed.wrapping_add(77), track_statistics: true,
6131 }
6132 } else {
6133 DataQualityConfig::minimal()
6134 };
6135 let mut injector = DataQualityInjector::new(config);
6136
6137 injector.set_country_pack(self.primary_pack().clone());
6139
6140 let context = HashMap::new();
6142
6143 for entry in entries.iter_mut() {
6144 if let Some(text) = &entry.header.header_text {
6146 let processed = injector.process_text_field(
6147 "header_text",
6148 text,
6149 &entry.header.document_id.to_string(),
6150 &context,
6151 );
6152 match processed {
6153 Some(new_text) if new_text != *text => {
6154 entry.header.header_text = Some(new_text);
6155 }
6156 None => {
6157 entry.header.header_text = None; }
6159 _ => {}
6160 }
6161 }
6162
6163 if let Some(ref_text) = &entry.header.reference {
6165 let processed = injector.process_text_field(
6166 "reference",
6167 ref_text,
6168 &entry.header.document_id.to_string(),
6169 &context,
6170 );
6171 match processed {
6172 Some(new_text) if new_text != *ref_text => {
6173 entry.header.reference = Some(new_text);
6174 }
6175 None => {
6176 entry.header.reference = None;
6177 }
6178 _ => {}
6179 }
6180 }
6181
6182 let user_persona = entry.header.user_persona.clone();
6184 if let Some(processed) = injector.process_text_field(
6185 "user_persona",
6186 &user_persona,
6187 &entry.header.document_id.to_string(),
6188 &context,
6189 ) {
6190 if processed != user_persona {
6191 entry.header.user_persona = processed;
6192 }
6193 }
6194
6195 for line in &mut entry.lines {
6197 if let Some(ref text) = line.line_text {
6199 let processed = injector.process_text_field(
6200 "line_text",
6201 text,
6202 &entry.header.document_id.to_string(),
6203 &context,
6204 );
6205 match processed {
6206 Some(new_text) if new_text != *text => {
6207 line.line_text = Some(new_text);
6208 }
6209 None => {
6210 line.line_text = None;
6211 }
6212 _ => {}
6213 }
6214 }
6215
6216 if let Some(cc) = &line.cost_center {
6218 let processed = injector.process_text_field(
6219 "cost_center",
6220 cc,
6221 &entry.header.document_id.to_string(),
6222 &context,
6223 );
6224 match processed {
6225 Some(new_cc) if new_cc != *cc => {
6226 line.cost_center = Some(new_cc);
6227 }
6228 None => {
6229 line.cost_center = None;
6230 }
6231 _ => {}
6232 }
6233 }
6234 }
6235
6236 if let Some(pb) = &pb {
6237 pb.inc(1);
6238 }
6239 }
6240
6241 if let Some(pb) = pb {
6242 pb.finish_with_message("Data quality injection complete");
6243 }
6244
6245 Ok(injector.stats().clone())
6246 }
6247
6248 fn generate_audit_data(&mut self, entries: &[JournalEntry]) -> SynthResult<AuditSnapshot> {
6259 let start_date = NaiveDate::parse_from_str(&self.config.global.start_date, "%Y-%m-%d")
6260 .map_err(|e| SynthError::config(format!("Invalid start_date: {}", e)))?;
6261 let fiscal_year = start_date.year() as u16;
6262 let period_end = start_date + chrono::Months::new(self.config.global.period_months);
6263
6264 let total_revenue: rust_decimal::Decimal = entries
6266 .iter()
6267 .flat_map(|e| e.lines.iter())
6268 .filter(|l| l.credit_amount > rust_decimal::Decimal::ZERO)
6269 .map(|l| l.credit_amount)
6270 .sum();
6271
6272 let total_items = (self.phase_config.audit_engagements * 50) as u64; let pb = self.create_progress_bar(total_items, "Generating Audit Data");
6274
6275 let mut snapshot = AuditSnapshot::default();
6276
6277 let mut engagement_gen = AuditEngagementGenerator::new(self.seed + 7000);
6279 let mut workpaper_gen = WorkpaperGenerator::new(self.seed + 7100);
6280 let mut evidence_gen = EvidenceGenerator::new(self.seed + 7200);
6281 let mut risk_gen = RiskAssessmentGenerator::new(self.seed + 7300);
6282 let mut finding_gen = FindingGenerator::new(self.seed + 7400);
6283 let mut judgment_gen = JudgmentGenerator::new(self.seed + 7500);
6284
6285 let accounts: Vec<String> = self
6287 .coa
6288 .as_ref()
6289 .map(|coa| {
6290 coa.get_postable_accounts()
6291 .iter()
6292 .map(|acc| acc.account_code().to_string())
6293 .collect()
6294 })
6295 .unwrap_or_default();
6296
6297 for (i, company) in self.config.companies.iter().enumerate() {
6299 let company_revenue = total_revenue
6301 * rust_decimal::Decimal::try_from(company.volume_weight).unwrap_or_default();
6302
6303 let engagements_for_company =
6305 self.phase_config.audit_engagements / self.config.companies.len().max(1);
6306 let extra = if i < self.phase_config.audit_engagements % self.config.companies.len() {
6307 1
6308 } else {
6309 0
6310 };
6311
6312 for _eng_idx in 0..(engagements_for_company + extra) {
6313 let mut engagement = engagement_gen.generate_engagement(
6315 &company.code,
6316 &company.name,
6317 fiscal_year,
6318 period_end,
6319 company_revenue,
6320 None, );
6322
6323 if !self.master_data.employees.is_empty() {
6325 let emp_count = self.master_data.employees.len();
6326 let base = (i * 10 + _eng_idx) % emp_count;
6328 engagement.engagement_partner_id = self.master_data.employees[base % emp_count]
6329 .employee_id
6330 .clone();
6331 engagement.engagement_manager_id = self.master_data.employees
6332 [(base + 1) % emp_count]
6333 .employee_id
6334 .clone();
6335 let real_team: Vec<String> = engagement
6336 .team_member_ids
6337 .iter()
6338 .enumerate()
6339 .map(|(j, _)| {
6340 self.master_data.employees[(base + 2 + j) % emp_count]
6341 .employee_id
6342 .clone()
6343 })
6344 .collect();
6345 engagement.team_member_ids = real_team;
6346 }
6347
6348 if let Some(pb) = &pb {
6349 pb.inc(1);
6350 }
6351
6352 let team_members: Vec<String> = engagement.team_member_ids.clone();
6354
6355 let workpapers =
6357 workpaper_gen.generate_complete_workpaper_set(&engagement, &team_members);
6358
6359 for wp in &workpapers {
6360 if let Some(pb) = &pb {
6361 pb.inc(1);
6362 }
6363
6364 let evidence = evidence_gen.generate_evidence_for_workpaper(
6366 wp,
6367 &team_members,
6368 wp.preparer_date,
6369 );
6370
6371 for _ in &evidence {
6372 if let Some(pb) = &pb {
6373 pb.inc(1);
6374 }
6375 }
6376
6377 snapshot.evidence.extend(evidence);
6378 }
6379
6380 let risks =
6382 risk_gen.generate_risks_for_engagement(&engagement, &team_members, &accounts);
6383
6384 for _ in &risks {
6385 if let Some(pb) = &pb {
6386 pb.inc(1);
6387 }
6388 }
6389 snapshot.risk_assessments.extend(risks);
6390
6391 let findings = finding_gen.generate_findings_for_engagement(
6393 &engagement,
6394 &workpapers,
6395 &team_members,
6396 );
6397
6398 for _ in &findings {
6399 if let Some(pb) = &pb {
6400 pb.inc(1);
6401 }
6402 }
6403 snapshot.findings.extend(findings);
6404
6405 let judgments =
6407 judgment_gen.generate_judgments_for_engagement(&engagement, &team_members);
6408
6409 for _ in &judgments {
6410 if let Some(pb) = &pb {
6411 pb.inc(1);
6412 }
6413 }
6414 snapshot.judgments.extend(judgments);
6415
6416 snapshot.workpapers.extend(workpapers);
6418 snapshot.engagements.push(engagement);
6419 }
6420 }
6421
6422 if let Some(pb) = pb {
6423 pb.finish_with_message(format!(
6424 "Audit data: {} engagements, {} workpapers, {} evidence",
6425 snapshot.engagements.len(),
6426 snapshot.workpapers.len(),
6427 snapshot.evidence.len()
6428 ));
6429 }
6430
6431 Ok(snapshot)
6432 }
6433
6434 fn export_graphs(
6441 &mut self,
6442 entries: &[JournalEntry],
6443 _coa: &Arc<ChartOfAccounts>,
6444 stats: &mut EnhancedGenerationStatistics,
6445 ) -> SynthResult<GraphExportSnapshot> {
6446 let pb = self.create_progress_bar(100, "Exporting Graphs");
6447
6448 let mut snapshot = GraphExportSnapshot::default();
6449
6450 let output_dir = self
6452 .output_path
6453 .clone()
6454 .unwrap_or_else(|| PathBuf::from(&self.config.output.output_directory));
6455 let graph_dir = output_dir.join(&self.config.graph_export.output_subdirectory);
6456
6457 for graph_type in &self.config.graph_export.graph_types {
6459 if let Some(pb) = &pb {
6460 pb.inc(10);
6461 }
6462
6463 let graph_config = TransactionGraphConfig {
6465 include_vendors: false,
6466 include_customers: false,
6467 create_debit_credit_edges: true,
6468 include_document_nodes: graph_type.include_document_nodes,
6469 min_edge_weight: graph_type.min_edge_weight,
6470 aggregate_parallel_edges: graph_type.aggregate_edges,
6471 };
6472
6473 let mut builder = TransactionGraphBuilder::new(graph_config);
6474 builder.add_journal_entries(entries);
6475 let graph = builder.build();
6476
6477 stats.graph_node_count += graph.node_count();
6479 stats.graph_edge_count += graph.edge_count();
6480
6481 if let Some(pb) = &pb {
6482 pb.inc(40);
6483 }
6484
6485 for format in &self.config.graph_export.formats {
6487 let format_dir = graph_dir.join(&graph_type.name).join(format_name(*format));
6488
6489 if let Err(e) = std::fs::create_dir_all(&format_dir) {
6491 warn!("Failed to create graph output directory: {}", e);
6492 continue;
6493 }
6494
6495 match format {
6496 datasynth_config::schema::GraphExportFormat::PytorchGeometric => {
6497 let pyg_config = PyGExportConfig {
6498 common: datasynth_graph::CommonExportConfig {
6499 export_node_features: true,
6500 export_edge_features: true,
6501 export_node_labels: true,
6502 export_edge_labels: true,
6503 export_masks: true,
6504 train_ratio: self.config.graph_export.train_ratio,
6505 val_ratio: self.config.graph_export.validation_ratio,
6506 seed: self.config.graph_export.split_seed.unwrap_or(self.seed),
6507 },
6508 one_hot_categoricals: false,
6509 };
6510
6511 let exporter = PyGExporter::new(pyg_config);
6512 match exporter.export(&graph, &format_dir) {
6513 Ok(metadata) => {
6514 snapshot.exports.insert(
6515 format!("{}_{}", graph_type.name, "pytorch_geometric"),
6516 GraphExportInfo {
6517 name: graph_type.name.clone(),
6518 format: "pytorch_geometric".to_string(),
6519 output_path: format_dir.clone(),
6520 node_count: metadata.num_nodes,
6521 edge_count: metadata.num_edges,
6522 },
6523 );
6524 snapshot.graph_count += 1;
6525 }
6526 Err(e) => {
6527 warn!("Failed to export PyTorch Geometric graph: {}", e);
6528 }
6529 }
6530 }
6531 datasynth_config::schema::GraphExportFormat::Neo4j => {
6532 warn!("Neo4j graph export is not yet implemented; skipping. Use 'pytorch_geometric' or 'rust_graph' format instead.");
6534 }
6535 datasynth_config::schema::GraphExportFormat::Dgl => {
6536 warn!("DGL graph export is not yet implemented; skipping. Use 'pytorch_geometric' or 'rust_graph' format instead.");
6538 }
6539 datasynth_config::schema::GraphExportFormat::RustGraph => {
6540 use datasynth_graph::{
6541 RustGraphExportConfig, RustGraphExporter, RustGraphOutputFormat,
6542 };
6543
6544 let rustgraph_config = RustGraphExportConfig {
6545 include_features: true,
6546 include_temporal: true,
6547 include_labels: true,
6548 source_name: "datasynth".to_string(),
6549 batch_id: None,
6550 output_format: RustGraphOutputFormat::JsonLines,
6551 export_node_properties: true,
6552 export_edge_properties: true,
6553 pretty_print: false,
6554 };
6555
6556 let exporter = RustGraphExporter::new(rustgraph_config);
6557 match exporter.export(&graph, &format_dir) {
6558 Ok(metadata) => {
6559 snapshot.exports.insert(
6560 format!("{}_{}", graph_type.name, "rustgraph"),
6561 GraphExportInfo {
6562 name: graph_type.name.clone(),
6563 format: "rustgraph".to_string(),
6564 output_path: format_dir.clone(),
6565 node_count: metadata.num_nodes,
6566 edge_count: metadata.num_edges,
6567 },
6568 );
6569 snapshot.graph_count += 1;
6570 }
6571 Err(e) => {
6572 warn!("Failed to export RustGraph: {}", e);
6573 }
6574 }
6575 }
6576 datasynth_config::schema::GraphExportFormat::RustGraphHypergraph => {
6577 debug!("RustGraphHypergraph format is handled in Phase 10b (hypergraph export)");
6579 }
6580 }
6581 }
6582
6583 if let Some(pb) = &pb {
6584 pb.inc(40);
6585 }
6586 }
6587
6588 stats.graph_export_count = snapshot.graph_count;
6589 snapshot.exported = snapshot.graph_count > 0;
6590
6591 if let Some(pb) = pb {
6592 pb.finish_with_message(format!(
6593 "Graphs exported: {} graphs ({} nodes, {} edges)",
6594 snapshot.graph_count, stats.graph_node_count, stats.graph_edge_count
6595 ));
6596 }
6597
6598 Ok(snapshot)
6599 }
6600
6601 fn build_additional_graphs(
6606 &self,
6607 banking: &BankingSnapshot,
6608 _intercompany: &IntercompanySnapshot,
6609 entries: &[JournalEntry],
6610 stats: &mut EnhancedGenerationStatistics,
6611 ) {
6612 let output_dir = self
6613 .output_path
6614 .clone()
6615 .unwrap_or_else(|| PathBuf::from(&self.config.output.output_directory));
6616 let graph_dir = output_dir.join(&self.config.graph_export.output_subdirectory);
6617
6618 if !banking.customers.is_empty() && !banking.transactions.is_empty() {
6620 info!("Phase 10c: Building banking network graph");
6621 let config = BankingGraphConfig::default();
6622 let mut builder = BankingGraphBuilder::new(config);
6623 builder.add_customers(&banking.customers);
6624 builder.add_accounts(&banking.accounts, &banking.customers);
6625 builder.add_transactions(&banking.transactions);
6626 let graph = builder.build();
6627
6628 let node_count = graph.node_count();
6629 let edge_count = graph.edge_count();
6630 stats.graph_node_count += node_count;
6631 stats.graph_edge_count += edge_count;
6632
6633 for format in &self.config.graph_export.formats {
6635 if matches!(
6636 format,
6637 datasynth_config::schema::GraphExportFormat::PytorchGeometric
6638 ) {
6639 let format_dir = graph_dir.join("banking_network").join("pytorch_geometric");
6640 if let Err(e) = std::fs::create_dir_all(&format_dir) {
6641 warn!("Failed to create banking graph output dir: {}", e);
6642 continue;
6643 }
6644 let pyg_config = PyGExportConfig::default();
6645 let exporter = PyGExporter::new(pyg_config);
6646 if let Err(e) = exporter.export(&graph, &format_dir) {
6647 warn!("Failed to export banking graph as PyG: {}", e);
6648 } else {
6649 info!(
6650 "Banking network graph exported: {} nodes, {} edges",
6651 node_count, edge_count
6652 );
6653 }
6654 }
6655 }
6656 }
6657
6658 let approval_entries: Vec<_> = entries
6660 .iter()
6661 .filter(|je| je.header.approval_workflow.is_some())
6662 .collect();
6663
6664 if !approval_entries.is_empty() {
6665 info!(
6666 "Phase 10c: Building approval network graph ({} entries with approvals)",
6667 approval_entries.len()
6668 );
6669 let config = ApprovalGraphConfig::default();
6670 let mut builder = ApprovalGraphBuilder::new(config);
6671
6672 for je in &approval_entries {
6673 if let Some(ref wf) = je.header.approval_workflow {
6674 for action in &wf.actions {
6675 let record = datasynth_core::models::ApprovalRecord {
6676 approval_id: format!(
6677 "APR-{}-{}",
6678 je.header.document_id, action.approval_level
6679 ),
6680 document_number: je.header.document_id.to_string(),
6681 document_type: "JE".to_string(),
6682 company_code: je.company_code().to_string(),
6683 requester_id: wf.preparer_id.clone(),
6684 requester_name: Some(wf.preparer_name.clone()),
6685 approver_id: action.actor_id.clone(),
6686 approver_name: action.actor_name.clone(),
6687 approval_date: je.posting_date(),
6688 action: format!("{:?}", action.action),
6689 amount: wf.amount,
6690 approval_limit: None,
6691 comments: action.comments.clone(),
6692 delegation_from: None,
6693 is_auto_approved: false,
6694 };
6695 builder.add_approval(&record);
6696 }
6697 }
6698 }
6699
6700 let graph = builder.build();
6701 let node_count = graph.node_count();
6702 let edge_count = graph.edge_count();
6703 stats.graph_node_count += node_count;
6704 stats.graph_edge_count += edge_count;
6705
6706 for format in &self.config.graph_export.formats {
6708 if matches!(
6709 format,
6710 datasynth_config::schema::GraphExportFormat::PytorchGeometric
6711 ) {
6712 let format_dir = graph_dir.join("approval_network").join("pytorch_geometric");
6713 if let Err(e) = std::fs::create_dir_all(&format_dir) {
6714 warn!("Failed to create approval graph output dir: {}", e);
6715 continue;
6716 }
6717 let pyg_config = PyGExportConfig::default();
6718 let exporter = PyGExporter::new(pyg_config);
6719 if let Err(e) = exporter.export(&graph, &format_dir) {
6720 warn!("Failed to export approval graph as PyG: {}", e);
6721 } else {
6722 info!(
6723 "Approval network graph exported: {} nodes, {} edges",
6724 node_count, edge_count
6725 );
6726 }
6727 }
6728 }
6729 }
6730
6731 debug!(
6734 "EntityGraphBuilder: skipped (requires Company→CompanyConfig mapping; \
6735 available when intercompany relationships are modeled as IntercompanyRelationship)"
6736 );
6737 }
6738
6739 #[allow(clippy::too_many_arguments)]
6746 fn export_hypergraph(
6747 &self,
6748 coa: &Arc<ChartOfAccounts>,
6749 entries: &[JournalEntry],
6750 document_flows: &DocumentFlowSnapshot,
6751 sourcing: &SourcingSnapshot,
6752 hr: &HrSnapshot,
6753 manufacturing: &ManufacturingSnapshot,
6754 banking: &BankingSnapshot,
6755 audit: &AuditSnapshot,
6756 financial_reporting: &FinancialReportingSnapshot,
6757 ocpm: &OcpmSnapshot,
6758 stats: &mut EnhancedGenerationStatistics,
6759 ) -> SynthResult<HypergraphExportInfo> {
6760 use datasynth_graph::builders::hypergraph::{HypergraphBuilder, HypergraphConfig};
6761 use datasynth_graph::exporters::hypergraph::{HypergraphExportConfig, HypergraphExporter};
6762 use datasynth_graph::exporters::unified::{RustGraphUnifiedExporter, UnifiedExportConfig};
6763 use datasynth_graph::models::hypergraph::AggregationStrategy;
6764
6765 let hg_settings = &self.config.graph_export.hypergraph;
6766
6767 let aggregation_strategy = match hg_settings.aggregation_strategy.as_str() {
6769 "truncate" => AggregationStrategy::Truncate,
6770 "pool_by_counterparty" => AggregationStrategy::PoolByCounterparty,
6771 "pool_by_time_period" => AggregationStrategy::PoolByTimePeriod,
6772 "importance_sample" => AggregationStrategy::ImportanceSample,
6773 _ => AggregationStrategy::PoolByCounterparty,
6774 };
6775
6776 let builder_config = HypergraphConfig {
6777 max_nodes: hg_settings.max_nodes,
6778 aggregation_strategy,
6779 include_coso: hg_settings.governance_layer.include_coso,
6780 include_controls: hg_settings.governance_layer.include_controls,
6781 include_sox: hg_settings.governance_layer.include_sox,
6782 include_vendors: hg_settings.governance_layer.include_vendors,
6783 include_customers: hg_settings.governance_layer.include_customers,
6784 include_employees: hg_settings.governance_layer.include_employees,
6785 include_p2p: hg_settings.process_layer.include_p2p,
6786 include_o2c: hg_settings.process_layer.include_o2c,
6787 include_s2c: hg_settings.process_layer.include_s2c,
6788 include_h2r: hg_settings.process_layer.include_h2r,
6789 include_mfg: hg_settings.process_layer.include_mfg,
6790 include_bank: hg_settings.process_layer.include_bank,
6791 include_audit: hg_settings.process_layer.include_audit,
6792 include_r2r: hg_settings.process_layer.include_r2r,
6793 events_as_hyperedges: hg_settings.process_layer.events_as_hyperedges,
6794 docs_per_counterparty_threshold: hg_settings
6795 .process_layer
6796 .docs_per_counterparty_threshold,
6797 include_accounts: hg_settings.accounting_layer.include_accounts,
6798 je_as_hyperedges: hg_settings.accounting_layer.je_as_hyperedges,
6799 include_cross_layer_edges: hg_settings.cross_layer.enabled,
6800 };
6801
6802 let mut builder = HypergraphBuilder::new(builder_config);
6803
6804 builder.add_coso_framework();
6806
6807 if hg_settings.governance_layer.include_controls && self.config.internal_controls.enabled {
6810 let controls = InternalControl::standard_controls();
6811 builder.add_controls(&controls);
6812 }
6813
6814 builder.add_vendors(&self.master_data.vendors);
6816 builder.add_customers(&self.master_data.customers);
6817 builder.add_employees(&self.master_data.employees);
6818
6819 builder.add_p2p_documents(
6821 &document_flows.purchase_orders,
6822 &document_flows.goods_receipts,
6823 &document_flows.vendor_invoices,
6824 &document_flows.payments,
6825 );
6826 builder.add_o2c_documents(
6827 &document_flows.sales_orders,
6828 &document_flows.deliveries,
6829 &document_flows.customer_invoices,
6830 );
6831 builder.add_s2c_documents(
6832 &sourcing.sourcing_projects,
6833 &sourcing.qualifications,
6834 &sourcing.rfx_events,
6835 &sourcing.bids,
6836 &sourcing.bid_evaluations,
6837 &sourcing.contracts,
6838 );
6839 builder.add_h2r_documents(&hr.payroll_runs, &hr.time_entries, &hr.expense_reports);
6840 builder.add_mfg_documents(
6841 &manufacturing.production_orders,
6842 &manufacturing.quality_inspections,
6843 &manufacturing.cycle_counts,
6844 );
6845 builder.add_bank_documents(&banking.customers, &banking.accounts, &banking.transactions);
6846 builder.add_audit_documents(
6847 &audit.engagements,
6848 &audit.workpapers,
6849 &audit.findings,
6850 &audit.evidence,
6851 &audit.risk_assessments,
6852 &audit.judgments,
6853 );
6854 builder.add_bank_recon_documents(&financial_reporting.bank_reconciliations);
6855
6856 if let Some(ref event_log) = ocpm.event_log {
6858 builder.add_ocpm_events(event_log);
6859 }
6860
6861 builder.add_accounts(coa);
6863 builder.add_journal_entries_as_hyperedges(entries);
6864
6865 let hypergraph = builder.build();
6867
6868 let output_dir = self
6870 .output_path
6871 .clone()
6872 .unwrap_or_else(|| PathBuf::from(&self.config.output.output_directory));
6873 let hg_dir = output_dir
6874 .join(&self.config.graph_export.output_subdirectory)
6875 .join(&hg_settings.output_subdirectory);
6876
6877 let (num_nodes, num_edges, num_hyperedges) = match hg_settings.output_format.as_str() {
6879 "unified" => {
6880 let exporter = RustGraphUnifiedExporter::new(UnifiedExportConfig::default());
6881 let metadata = exporter.export(&hypergraph, &hg_dir).map_err(|e| {
6882 SynthError::generation(format!("Unified hypergraph export failed: {}", e))
6883 })?;
6884 (
6885 metadata.num_nodes,
6886 metadata.num_edges,
6887 metadata.num_hyperedges,
6888 )
6889 }
6890 _ => {
6891 let exporter = HypergraphExporter::new(HypergraphExportConfig::default());
6893 let metadata = exporter.export(&hypergraph, &hg_dir).map_err(|e| {
6894 SynthError::generation(format!("Hypergraph export failed: {}", e))
6895 })?;
6896 (
6897 metadata.num_nodes,
6898 metadata.num_edges,
6899 metadata.num_hyperedges,
6900 )
6901 }
6902 };
6903
6904 #[cfg(feature = "streaming")]
6906 if let Some(ref target_url) = hg_settings.stream_target {
6907 use crate::stream_client::{StreamClient, StreamConfig};
6908 use std::io::Write as _;
6909
6910 let api_key = std::env::var("RUSTGRAPH_API_KEY").ok();
6911 let stream_config = StreamConfig {
6912 target_url: target_url.clone(),
6913 batch_size: hg_settings.stream_batch_size,
6914 api_key,
6915 ..StreamConfig::default()
6916 };
6917
6918 match StreamClient::new(stream_config) {
6919 Ok(mut client) => {
6920 let exporter = RustGraphUnifiedExporter::new(UnifiedExportConfig::default());
6921 match exporter.export_to_writer(&hypergraph, &mut client) {
6922 Ok(_) => {
6923 if let Err(e) = client.flush() {
6924 warn!("Failed to flush stream client: {}", e);
6925 } else {
6926 info!("Streamed {} records to {}", client.total_sent(), target_url);
6927 }
6928 }
6929 Err(e) => {
6930 warn!("Streaming export failed: {}", e);
6931 }
6932 }
6933 }
6934 Err(e) => {
6935 warn!("Failed to create stream client: {}", e);
6936 }
6937 }
6938 }
6939
6940 stats.graph_node_count += num_nodes;
6942 stats.graph_edge_count += num_edges;
6943 stats.graph_export_count += 1;
6944
6945 Ok(HypergraphExportInfo {
6946 node_count: num_nodes,
6947 edge_count: num_edges,
6948 hyperedge_count: num_hyperedges,
6949 output_path: hg_dir,
6950 })
6951 }
6952
6953 fn generate_banking_data(&mut self) -> SynthResult<BankingSnapshot> {
6958 let pb = self.create_progress_bar(100, "Generating Banking Data");
6959
6960 let orchestrator = BankingOrchestratorBuilder::new()
6962 .config(self.config.banking.clone())
6963 .seed(self.seed + 9000)
6964 .country_pack(self.primary_pack().clone())
6965 .build();
6966
6967 if let Some(pb) = &pb {
6968 pb.inc(10);
6969 }
6970
6971 let result = orchestrator.generate();
6973
6974 if let Some(pb) = &pb {
6975 pb.inc(90);
6976 pb.finish_with_message(format!(
6977 "Banking: {} customers, {} transactions",
6978 result.customers.len(),
6979 result.transactions.len()
6980 ));
6981 }
6982
6983 let mut banking_customers = result.customers;
6988 let core_customers = &self.master_data.customers;
6989 if !core_customers.is_empty() {
6990 for (i, bc) in banking_customers.iter_mut().enumerate() {
6991 let core = &core_customers[i % core_customers.len()];
6992 bc.name = CustomerName::business(&core.name);
6993 bc.residence_country = core.country.clone();
6994 bc.enterprise_customer_id = Some(core.customer_id.clone());
6995 }
6996 debug!(
6997 "Cross-referenced {} banking customers with {} core customers",
6998 banking_customers.len(),
6999 core_customers.len()
7000 );
7001 }
7002
7003 Ok(BankingSnapshot {
7004 customers: banking_customers,
7005 accounts: result.accounts,
7006 transactions: result.transactions,
7007 transaction_labels: result.transaction_labels,
7008 customer_labels: result.customer_labels,
7009 account_labels: result.account_labels,
7010 relationship_labels: result.relationship_labels,
7011 narratives: result.narratives,
7012 suspicious_count: result.stats.suspicious_count,
7013 scenario_count: result.scenarios.len(),
7014 })
7015 }
7016
7017 fn calculate_total_transactions(&self) -> u64 {
7019 let months = self.config.global.period_months as f64;
7020 self.config
7021 .companies
7022 .iter()
7023 .map(|c| {
7024 let annual = c.annual_transaction_volume.count() as f64;
7025 let weighted = annual * c.volume_weight;
7026 (weighted * months / 12.0) as u64
7027 })
7028 .sum()
7029 }
7030
7031 fn create_progress_bar(&self, total: u64, message: &str) -> Option<ProgressBar> {
7033 if !self.phase_config.show_progress {
7034 return None;
7035 }
7036
7037 let pb = if let Some(mp) = &self.multi_progress {
7038 mp.add(ProgressBar::new(total))
7039 } else {
7040 ProgressBar::new(total)
7041 };
7042
7043 pb.set_style(
7044 ProgressStyle::default_bar()
7045 .template(&format!(
7046 "{{spinner:.green}} {} [{{elapsed_precise}}] [{{bar:40.cyan/blue}}] {{pos}}/{{len}} ({{per_sec}})",
7047 message
7048 ))
7049 .expect("Progress bar template should be valid - uses only standard indicatif placeholders")
7050 .progress_chars("#>-"),
7051 );
7052
7053 Some(pb)
7054 }
7055
7056 pub fn get_coa(&self) -> Option<Arc<ChartOfAccounts>> {
7058 self.coa.clone()
7059 }
7060
7061 pub fn get_master_data(&self) -> &MasterDataSnapshot {
7063 &self.master_data
7064 }
7065
7066 fn build_lineage_graph(&self) -> super::lineage::LineageGraph {
7068 use super::lineage::LineageGraphBuilder;
7069
7070 let mut builder = LineageGraphBuilder::new();
7071
7072 builder.add_config_section("config:global", "Global Config");
7074 builder.add_config_section("config:chart_of_accounts", "Chart of Accounts Config");
7075 builder.add_config_section("config:transactions", "Transaction Config");
7076
7077 builder.add_generator_phase("phase:coa", "Chart of Accounts Generation");
7079 builder.add_generator_phase("phase:je", "Journal Entry Generation");
7080
7081 builder.configured_by("phase:coa", "config:chart_of_accounts");
7083 builder.configured_by("phase:je", "config:transactions");
7084
7085 builder.add_output_file("output:je", "Journal Entries", "sample_entries.json");
7087 builder.produced_by("output:je", "phase:je");
7088
7089 if self.phase_config.generate_master_data {
7091 builder.add_config_section("config:master_data", "Master Data Config");
7092 builder.add_generator_phase("phase:master_data", "Master Data Generation");
7093 builder.configured_by("phase:master_data", "config:master_data");
7094 builder.input_to("phase:master_data", "phase:je");
7095 }
7096
7097 if self.phase_config.generate_document_flows {
7098 builder.add_config_section("config:document_flows", "Document Flow Config");
7099 builder.add_generator_phase("phase:p2p", "P2P Document Flow");
7100 builder.add_generator_phase("phase:o2c", "O2C Document Flow");
7101 builder.configured_by("phase:p2p", "config:document_flows");
7102 builder.configured_by("phase:o2c", "config:document_flows");
7103
7104 builder.add_output_file("output:po", "Purchase Orders", "purchase_orders.csv");
7105 builder.add_output_file("output:gr", "Goods Receipts", "goods_receipts.csv");
7106 builder.add_output_file("output:vi", "Vendor Invoices", "vendor_invoices.csv");
7107 builder.add_output_file("output:so", "Sales Orders", "sales_orders.csv");
7108 builder.add_output_file("output:ci", "Customer Invoices", "customer_invoices.csv");
7109
7110 builder.produced_by("output:po", "phase:p2p");
7111 builder.produced_by("output:gr", "phase:p2p");
7112 builder.produced_by("output:vi", "phase:p2p");
7113 builder.produced_by("output:so", "phase:o2c");
7114 builder.produced_by("output:ci", "phase:o2c");
7115 }
7116
7117 if self.phase_config.inject_anomalies {
7118 builder.add_config_section("config:fraud", "Fraud/Anomaly Config");
7119 builder.add_generator_phase("phase:anomaly", "Anomaly Injection");
7120 builder.configured_by("phase:anomaly", "config:fraud");
7121 builder.add_output_file(
7122 "output:labels",
7123 "Anomaly Labels",
7124 "labels/anomaly_labels.csv",
7125 );
7126 builder.produced_by("output:labels", "phase:anomaly");
7127 }
7128
7129 if self.phase_config.generate_audit {
7130 builder.add_config_section("config:audit", "Audit Config");
7131 builder.add_generator_phase("phase:audit", "Audit Data Generation");
7132 builder.configured_by("phase:audit", "config:audit");
7133 }
7134
7135 if self.phase_config.generate_banking {
7136 builder.add_config_section("config:banking", "Banking Config");
7137 builder.add_generator_phase("phase:banking", "Banking KYC/AML Generation");
7138 builder.configured_by("phase:banking", "config:banking");
7139 }
7140
7141 if self.config.llm.enabled {
7142 builder.add_config_section("config:llm", "LLM Enrichment Config");
7143 builder.add_generator_phase("phase:llm_enrichment", "LLM Enrichment");
7144 builder.configured_by("phase:llm_enrichment", "config:llm");
7145 }
7146
7147 if self.config.diffusion.enabled {
7148 builder.add_config_section("config:diffusion", "Diffusion Enhancement Config");
7149 builder.add_generator_phase("phase:diffusion", "Diffusion Enhancement");
7150 builder.configured_by("phase:diffusion", "config:diffusion");
7151 }
7152
7153 if self.config.causal.enabled {
7154 builder.add_config_section("config:causal", "Causal Generation Config");
7155 builder.add_generator_phase("phase:causal", "Causal Overlay");
7156 builder.configured_by("phase:causal", "config:causal");
7157 }
7158
7159 builder.build()
7160 }
7161}
7162
7163fn format_name(format: datasynth_config::schema::GraphExportFormat) -> &'static str {
7165 match format {
7166 datasynth_config::schema::GraphExportFormat::PytorchGeometric => "pytorch_geometric",
7167 datasynth_config::schema::GraphExportFormat::Neo4j => "neo4j",
7168 datasynth_config::schema::GraphExportFormat::Dgl => "dgl",
7169 datasynth_config::schema::GraphExportFormat::RustGraph => "rustgraph",
7170 datasynth_config::schema::GraphExportFormat::RustGraphHypergraph => "rustgraph_hypergraph",
7171 }
7172}
7173
7174#[cfg(test)]
7175#[allow(clippy::unwrap_used)]
7176mod tests {
7177 use super::*;
7178 use datasynth_config::schema::*;
7179
7180 fn create_test_config() -> GeneratorConfig {
7181 GeneratorConfig {
7182 global: GlobalConfig {
7183 industry: IndustrySector::Manufacturing,
7184 start_date: "2024-01-01".to_string(),
7185 period_months: 1,
7186 seed: Some(42),
7187 parallel: false,
7188 group_currency: "USD".to_string(),
7189 worker_threads: 0,
7190 memory_limit_mb: 0,
7191 },
7192 companies: vec![CompanyConfig {
7193 code: "1000".to_string(),
7194 name: "Test Company".to_string(),
7195 currency: "USD".to_string(),
7196 country: "US".to_string(),
7197 annual_transaction_volume: TransactionVolume::TenK,
7198 volume_weight: 1.0,
7199 fiscal_year_variant: "K4".to_string(),
7200 }],
7201 chart_of_accounts: ChartOfAccountsConfig {
7202 complexity: CoAComplexity::Small,
7203 industry_specific: true,
7204 custom_accounts: None,
7205 min_hierarchy_depth: 2,
7206 max_hierarchy_depth: 4,
7207 },
7208 transactions: TransactionConfig::default(),
7209 output: OutputConfig::default(),
7210 fraud: FraudConfig::default(),
7211 internal_controls: InternalControlsConfig::default(),
7212 business_processes: BusinessProcessConfig::default(),
7213 user_personas: UserPersonaConfig::default(),
7214 templates: TemplateConfig::default(),
7215 approval: ApprovalConfig::default(),
7216 departments: DepartmentConfig::default(),
7217 master_data: MasterDataConfig::default(),
7218 document_flows: DocumentFlowConfig::default(),
7219 intercompany: IntercompanyConfig::default(),
7220 balance: BalanceConfig::default(),
7221 ocpm: OcpmConfig::default(),
7222 audit: AuditGenerationConfig::default(),
7223 banking: datasynth_banking::BankingConfig::default(),
7224 data_quality: DataQualitySchemaConfig::default(),
7225 scenario: ScenarioConfig::default(),
7226 temporal: TemporalDriftConfig::default(),
7227 graph_export: GraphExportConfig::default(),
7228 streaming: StreamingSchemaConfig::default(),
7229 rate_limit: RateLimitSchemaConfig::default(),
7230 temporal_attributes: TemporalAttributeSchemaConfig::default(),
7231 relationships: RelationshipSchemaConfig::default(),
7232 accounting_standards: AccountingStandardsConfig::default(),
7233 audit_standards: AuditStandardsConfig::default(),
7234 distributions: Default::default(),
7235 temporal_patterns: Default::default(),
7236 vendor_network: VendorNetworkSchemaConfig::default(),
7237 customer_segmentation: CustomerSegmentationSchemaConfig::default(),
7238 relationship_strength: RelationshipStrengthSchemaConfig::default(),
7239 cross_process_links: CrossProcessLinksSchemaConfig::default(),
7240 organizational_events: OrganizationalEventsSchemaConfig::default(),
7241 behavioral_drift: BehavioralDriftSchemaConfig::default(),
7242 market_drift: MarketDriftSchemaConfig::default(),
7243 drift_labeling: DriftLabelingSchemaConfig::default(),
7244 anomaly_injection: Default::default(),
7245 industry_specific: Default::default(),
7246 fingerprint_privacy: Default::default(),
7247 quality_gates: Default::default(),
7248 compliance: Default::default(),
7249 webhooks: Default::default(),
7250 llm: Default::default(),
7251 diffusion: Default::default(),
7252 causal: Default::default(),
7253 source_to_pay: Default::default(),
7254 financial_reporting: Default::default(),
7255 hr: Default::default(),
7256 manufacturing: Default::default(),
7257 sales_quotes: Default::default(),
7258 tax: Default::default(),
7259 treasury: Default::default(),
7260 project_accounting: Default::default(),
7261 esg: Default::default(),
7262 country_packs: None,
7263 }
7264 }
7265
7266 #[test]
7267 fn test_enhanced_orchestrator_creation() {
7268 let config = create_test_config();
7269 let orchestrator = EnhancedOrchestrator::with_defaults(config);
7270 assert!(orchestrator.is_ok());
7271 }
7272
7273 #[test]
7274 fn test_minimal_generation() {
7275 let config = create_test_config();
7276 let phase_config = PhaseConfig {
7277 generate_master_data: false,
7278 generate_document_flows: false,
7279 generate_journal_entries: true,
7280 inject_anomalies: false,
7281 show_progress: false,
7282 ..Default::default()
7283 };
7284
7285 let mut orchestrator = EnhancedOrchestrator::new(config, phase_config).unwrap();
7286 let result = orchestrator.generate();
7287
7288 assert!(result.is_ok());
7289 let result = result.unwrap();
7290 assert!(!result.journal_entries.is_empty());
7291 }
7292
7293 #[test]
7294 fn test_master_data_generation() {
7295 let config = create_test_config();
7296 let phase_config = PhaseConfig {
7297 generate_master_data: true,
7298 generate_document_flows: false,
7299 generate_journal_entries: false,
7300 inject_anomalies: false,
7301 show_progress: false,
7302 vendors_per_company: 5,
7303 customers_per_company: 5,
7304 materials_per_company: 10,
7305 assets_per_company: 5,
7306 employees_per_company: 10,
7307 ..Default::default()
7308 };
7309
7310 let mut orchestrator = EnhancedOrchestrator::new(config, phase_config).unwrap();
7311 let result = orchestrator.generate().unwrap();
7312
7313 assert!(!result.master_data.vendors.is_empty());
7314 assert!(!result.master_data.customers.is_empty());
7315 assert!(!result.master_data.materials.is_empty());
7316 }
7317
7318 #[test]
7319 fn test_document_flow_generation() {
7320 let config = create_test_config();
7321 let phase_config = PhaseConfig {
7322 generate_master_data: true,
7323 generate_document_flows: true,
7324 generate_journal_entries: false,
7325 inject_anomalies: false,
7326 inject_data_quality: false,
7327 validate_balances: false,
7328 generate_ocpm_events: false,
7329 show_progress: false,
7330 vendors_per_company: 5,
7331 customers_per_company: 5,
7332 materials_per_company: 10,
7333 assets_per_company: 5,
7334 employees_per_company: 10,
7335 p2p_chains: 5,
7336 o2c_chains: 5,
7337 ..Default::default()
7338 };
7339
7340 let mut orchestrator = EnhancedOrchestrator::new(config, phase_config).unwrap();
7341 let result = orchestrator.generate().unwrap();
7342
7343 assert!(!result.document_flows.p2p_chains.is_empty());
7345 assert!(!result.document_flows.o2c_chains.is_empty());
7346
7347 assert!(!result.document_flows.purchase_orders.is_empty());
7349 assert!(!result.document_flows.sales_orders.is_empty());
7350 }
7351
7352 #[test]
7353 fn test_anomaly_injection() {
7354 let config = create_test_config();
7355 let phase_config = PhaseConfig {
7356 generate_master_data: false,
7357 generate_document_flows: false,
7358 generate_journal_entries: true,
7359 inject_anomalies: true,
7360 show_progress: false,
7361 ..Default::default()
7362 };
7363
7364 let mut orchestrator = EnhancedOrchestrator::new(config, phase_config).unwrap();
7365 let result = orchestrator.generate().unwrap();
7366
7367 assert!(!result.journal_entries.is_empty());
7369
7370 assert!(result.anomaly_labels.summary.is_some());
7373 }
7374
7375 #[test]
7376 fn test_full_generation_pipeline() {
7377 let config = create_test_config();
7378 let phase_config = PhaseConfig {
7379 generate_master_data: true,
7380 generate_document_flows: true,
7381 generate_journal_entries: true,
7382 inject_anomalies: false,
7383 inject_data_quality: false,
7384 validate_balances: true,
7385 generate_ocpm_events: false,
7386 show_progress: false,
7387 vendors_per_company: 3,
7388 customers_per_company: 3,
7389 materials_per_company: 5,
7390 assets_per_company: 3,
7391 employees_per_company: 5,
7392 p2p_chains: 3,
7393 o2c_chains: 3,
7394 ..Default::default()
7395 };
7396
7397 let mut orchestrator = EnhancedOrchestrator::new(config, phase_config).unwrap();
7398 let result = orchestrator.generate().unwrap();
7399
7400 assert!(!result.master_data.vendors.is_empty());
7402 assert!(!result.master_data.customers.is_empty());
7403 assert!(!result.document_flows.p2p_chains.is_empty());
7404 assert!(!result.document_flows.o2c_chains.is_empty());
7405 assert!(!result.journal_entries.is_empty());
7406 assert!(result.statistics.accounts_count > 0);
7407
7408 assert!(!result.subledger.ap_invoices.is_empty());
7410 assert!(!result.subledger.ar_invoices.is_empty());
7411
7412 assert!(result.balance_validation.validated);
7414 assert!(result.balance_validation.entries_processed > 0);
7415 }
7416
7417 #[test]
7418 fn test_subledger_linking() {
7419 let config = create_test_config();
7420 let phase_config = PhaseConfig {
7421 generate_master_data: true,
7422 generate_document_flows: true,
7423 generate_journal_entries: false,
7424 inject_anomalies: false,
7425 inject_data_quality: false,
7426 validate_balances: false,
7427 generate_ocpm_events: false,
7428 show_progress: false,
7429 vendors_per_company: 5,
7430 customers_per_company: 5,
7431 materials_per_company: 10,
7432 assets_per_company: 3,
7433 employees_per_company: 5,
7434 p2p_chains: 5,
7435 o2c_chains: 5,
7436 ..Default::default()
7437 };
7438
7439 let mut orchestrator = EnhancedOrchestrator::new(config, phase_config).unwrap();
7440 let result = orchestrator.generate().unwrap();
7441
7442 assert!(!result.document_flows.vendor_invoices.is_empty());
7444 assert!(!result.document_flows.customer_invoices.is_empty());
7445
7446 assert!(!result.subledger.ap_invoices.is_empty());
7448 assert!(!result.subledger.ar_invoices.is_empty());
7449
7450 assert_eq!(
7452 result.subledger.ap_invoices.len(),
7453 result.document_flows.vendor_invoices.len()
7454 );
7455
7456 assert_eq!(
7458 result.subledger.ar_invoices.len(),
7459 result.document_flows.customer_invoices.len()
7460 );
7461
7462 assert_eq!(
7464 result.statistics.ap_invoice_count,
7465 result.subledger.ap_invoices.len()
7466 );
7467 assert_eq!(
7468 result.statistics.ar_invoice_count,
7469 result.subledger.ar_invoices.len()
7470 );
7471 }
7472
7473 #[test]
7474 fn test_balance_validation() {
7475 let config = create_test_config();
7476 let phase_config = PhaseConfig {
7477 generate_master_data: false,
7478 generate_document_flows: false,
7479 generate_journal_entries: true,
7480 inject_anomalies: false,
7481 validate_balances: true,
7482 show_progress: false,
7483 ..Default::default()
7484 };
7485
7486 let mut orchestrator = EnhancedOrchestrator::new(config, phase_config).unwrap();
7487 let result = orchestrator.generate().unwrap();
7488
7489 assert!(result.balance_validation.validated);
7491 assert!(result.balance_validation.entries_processed > 0);
7492
7493 assert!(!result.balance_validation.has_unbalanced_entries);
7495
7496 assert_eq!(
7498 result.balance_validation.total_debits,
7499 result.balance_validation.total_credits
7500 );
7501 }
7502
7503 #[test]
7504 fn test_statistics_accuracy() {
7505 let config = create_test_config();
7506 let phase_config = PhaseConfig {
7507 generate_master_data: true,
7508 generate_document_flows: false,
7509 generate_journal_entries: true,
7510 inject_anomalies: false,
7511 show_progress: false,
7512 vendors_per_company: 10,
7513 customers_per_company: 20,
7514 materials_per_company: 15,
7515 assets_per_company: 5,
7516 employees_per_company: 8,
7517 ..Default::default()
7518 };
7519
7520 let mut orchestrator = EnhancedOrchestrator::new(config, phase_config).unwrap();
7521 let result = orchestrator.generate().unwrap();
7522
7523 assert_eq!(
7525 result.statistics.vendor_count,
7526 result.master_data.vendors.len()
7527 );
7528 assert_eq!(
7529 result.statistics.customer_count,
7530 result.master_data.customers.len()
7531 );
7532 assert_eq!(
7533 result.statistics.material_count,
7534 result.master_data.materials.len()
7535 );
7536 assert_eq!(
7537 result.statistics.total_entries as usize,
7538 result.journal_entries.len()
7539 );
7540 }
7541
7542 #[test]
7543 fn test_phase_config_defaults() {
7544 let config = PhaseConfig::default();
7545 assert!(config.generate_master_data);
7546 assert!(config.generate_document_flows);
7547 assert!(config.generate_journal_entries);
7548 assert!(!config.inject_anomalies);
7549 assert!(config.validate_balances);
7550 assert!(config.show_progress);
7551 assert!(config.vendors_per_company > 0);
7552 assert!(config.customers_per_company > 0);
7553 }
7554
7555 #[test]
7556 fn test_get_coa_before_generation() {
7557 let config = create_test_config();
7558 let orchestrator = EnhancedOrchestrator::with_defaults(config).unwrap();
7559
7560 assert!(orchestrator.get_coa().is_none());
7562 }
7563
7564 #[test]
7565 fn test_get_coa_after_generation() {
7566 let config = create_test_config();
7567 let phase_config = PhaseConfig {
7568 generate_master_data: false,
7569 generate_document_flows: false,
7570 generate_journal_entries: true,
7571 inject_anomalies: false,
7572 show_progress: false,
7573 ..Default::default()
7574 };
7575
7576 let mut orchestrator = EnhancedOrchestrator::new(config, phase_config).unwrap();
7577 let _ = orchestrator.generate().unwrap();
7578
7579 assert!(orchestrator.get_coa().is_some());
7581 }
7582
7583 #[test]
7584 fn test_get_master_data() {
7585 let config = create_test_config();
7586 let phase_config = PhaseConfig {
7587 generate_master_data: true,
7588 generate_document_flows: false,
7589 generate_journal_entries: false,
7590 inject_anomalies: false,
7591 show_progress: false,
7592 vendors_per_company: 5,
7593 customers_per_company: 5,
7594 materials_per_company: 5,
7595 assets_per_company: 5,
7596 employees_per_company: 5,
7597 ..Default::default()
7598 };
7599
7600 let mut orchestrator = EnhancedOrchestrator::new(config, phase_config).unwrap();
7601 let _ = orchestrator.generate().unwrap();
7602
7603 let master_data = orchestrator.get_master_data();
7604 assert!(!master_data.vendors.is_empty());
7605 }
7606
7607 #[test]
7608 fn test_with_progress_builder() {
7609 let config = create_test_config();
7610 let orchestrator = EnhancedOrchestrator::with_defaults(config)
7611 .unwrap()
7612 .with_progress(false);
7613
7614 assert!(!orchestrator.phase_config.show_progress);
7616 }
7617
7618 #[test]
7619 fn test_multi_company_generation() {
7620 let mut config = create_test_config();
7621 config.companies.push(CompanyConfig {
7622 code: "2000".to_string(),
7623 name: "Subsidiary".to_string(),
7624 currency: "EUR".to_string(),
7625 country: "DE".to_string(),
7626 annual_transaction_volume: TransactionVolume::TenK,
7627 volume_weight: 0.5,
7628 fiscal_year_variant: "K4".to_string(),
7629 });
7630
7631 let phase_config = PhaseConfig {
7632 generate_master_data: true,
7633 generate_document_flows: false,
7634 generate_journal_entries: true,
7635 inject_anomalies: false,
7636 show_progress: false,
7637 vendors_per_company: 5,
7638 customers_per_company: 5,
7639 materials_per_company: 5,
7640 assets_per_company: 5,
7641 employees_per_company: 5,
7642 ..Default::default()
7643 };
7644
7645 let mut orchestrator = EnhancedOrchestrator::new(config, phase_config).unwrap();
7646 let result = orchestrator.generate().unwrap();
7647
7648 assert!(result.statistics.vendor_count >= 10); assert!(result.statistics.customer_count >= 10);
7651 assert!(result.statistics.companies_count == 2);
7652 }
7653
7654 #[test]
7655 fn test_empty_master_data_skips_document_flows() {
7656 let config = create_test_config();
7657 let phase_config = PhaseConfig {
7658 generate_master_data: false, generate_document_flows: true, generate_journal_entries: false,
7661 inject_anomalies: false,
7662 show_progress: false,
7663 ..Default::default()
7664 };
7665
7666 let mut orchestrator = EnhancedOrchestrator::new(config, phase_config).unwrap();
7667 let result = orchestrator.generate().unwrap();
7668
7669 assert!(result.document_flows.p2p_chains.is_empty());
7671 assert!(result.document_flows.o2c_chains.is_empty());
7672 }
7673
7674 #[test]
7675 fn test_journal_entry_line_item_count() {
7676 let config = create_test_config();
7677 let phase_config = PhaseConfig {
7678 generate_master_data: false,
7679 generate_document_flows: false,
7680 generate_journal_entries: true,
7681 inject_anomalies: false,
7682 show_progress: false,
7683 ..Default::default()
7684 };
7685
7686 let mut orchestrator = EnhancedOrchestrator::new(config, phase_config).unwrap();
7687 let result = orchestrator.generate().unwrap();
7688
7689 let calculated_line_items: u64 = result
7691 .journal_entries
7692 .iter()
7693 .map(|e| e.line_count() as u64)
7694 .sum();
7695 assert_eq!(result.statistics.total_line_items, calculated_line_items);
7696 }
7697
7698 #[test]
7699 fn test_audit_generation() {
7700 let config = create_test_config();
7701 let phase_config = PhaseConfig {
7702 generate_master_data: false,
7703 generate_document_flows: false,
7704 generate_journal_entries: true,
7705 inject_anomalies: false,
7706 show_progress: false,
7707 generate_audit: true,
7708 audit_engagements: 2,
7709 workpapers_per_engagement: 5,
7710 evidence_per_workpaper: 2,
7711 risks_per_engagement: 3,
7712 findings_per_engagement: 2,
7713 judgments_per_engagement: 2,
7714 ..Default::default()
7715 };
7716
7717 let mut orchestrator = EnhancedOrchestrator::new(config, phase_config).unwrap();
7718 let result = orchestrator.generate().unwrap();
7719
7720 assert_eq!(result.audit.engagements.len(), 2);
7722 assert!(!result.audit.workpapers.is_empty());
7723 assert!(!result.audit.evidence.is_empty());
7724 assert!(!result.audit.risk_assessments.is_empty());
7725 assert!(!result.audit.findings.is_empty());
7726 assert!(!result.audit.judgments.is_empty());
7727
7728 assert_eq!(
7730 result.statistics.audit_engagement_count,
7731 result.audit.engagements.len()
7732 );
7733 assert_eq!(
7734 result.statistics.audit_workpaper_count,
7735 result.audit.workpapers.len()
7736 );
7737 assert_eq!(
7738 result.statistics.audit_evidence_count,
7739 result.audit.evidence.len()
7740 );
7741 assert_eq!(
7742 result.statistics.audit_risk_count,
7743 result.audit.risk_assessments.len()
7744 );
7745 assert_eq!(
7746 result.statistics.audit_finding_count,
7747 result.audit.findings.len()
7748 );
7749 assert_eq!(
7750 result.statistics.audit_judgment_count,
7751 result.audit.judgments.len()
7752 );
7753 }
7754
7755 #[test]
7756 fn test_new_phases_disabled_by_default() {
7757 let config = create_test_config();
7758 assert!(!config.llm.enabled);
7760 assert!(!config.diffusion.enabled);
7761 assert!(!config.causal.enabled);
7762
7763 let phase_config = PhaseConfig {
7764 generate_master_data: false,
7765 generate_document_flows: false,
7766 generate_journal_entries: true,
7767 inject_anomalies: false,
7768 show_progress: false,
7769 ..Default::default()
7770 };
7771
7772 let mut orchestrator = EnhancedOrchestrator::new(config, phase_config).unwrap();
7773 let result = orchestrator.generate().unwrap();
7774
7775 assert_eq!(result.statistics.llm_enrichment_ms, 0);
7777 assert_eq!(result.statistics.llm_vendors_enriched, 0);
7778 assert_eq!(result.statistics.diffusion_enhancement_ms, 0);
7779 assert_eq!(result.statistics.diffusion_samples_generated, 0);
7780 assert_eq!(result.statistics.causal_generation_ms, 0);
7781 assert_eq!(result.statistics.causal_samples_generated, 0);
7782 assert!(result.statistics.causal_validation_passed.is_none());
7783 }
7784
7785 #[test]
7786 fn test_llm_enrichment_enabled() {
7787 let mut config = create_test_config();
7788 config.llm.enabled = true;
7789 config.llm.max_vendor_enrichments = 3;
7790
7791 let phase_config = PhaseConfig {
7792 generate_master_data: true,
7793 generate_document_flows: false,
7794 generate_journal_entries: false,
7795 inject_anomalies: false,
7796 show_progress: false,
7797 vendors_per_company: 5,
7798 customers_per_company: 3,
7799 materials_per_company: 3,
7800 assets_per_company: 3,
7801 employees_per_company: 3,
7802 ..Default::default()
7803 };
7804
7805 let mut orchestrator = EnhancedOrchestrator::new(config, phase_config).unwrap();
7806 let result = orchestrator.generate().unwrap();
7807
7808 assert!(result.statistics.llm_vendors_enriched > 0);
7810 assert!(result.statistics.llm_vendors_enriched <= 3);
7811 }
7812
7813 #[test]
7814 fn test_diffusion_enhancement_enabled() {
7815 let mut config = create_test_config();
7816 config.diffusion.enabled = true;
7817 config.diffusion.n_steps = 50;
7818 config.diffusion.sample_size = 20;
7819
7820 let phase_config = PhaseConfig {
7821 generate_master_data: false,
7822 generate_document_flows: false,
7823 generate_journal_entries: true,
7824 inject_anomalies: false,
7825 show_progress: false,
7826 ..Default::default()
7827 };
7828
7829 let mut orchestrator = EnhancedOrchestrator::new(config, phase_config).unwrap();
7830 let result = orchestrator.generate().unwrap();
7831
7832 assert_eq!(result.statistics.diffusion_samples_generated, 20);
7834 }
7835
7836 #[test]
7837 fn test_causal_overlay_enabled() {
7838 let mut config = create_test_config();
7839 config.causal.enabled = true;
7840 config.causal.template = "fraud_detection".to_string();
7841 config.causal.sample_size = 100;
7842 config.causal.validate = true;
7843
7844 let phase_config = PhaseConfig {
7845 generate_master_data: false,
7846 generate_document_flows: false,
7847 generate_journal_entries: true,
7848 inject_anomalies: false,
7849 show_progress: false,
7850 ..Default::default()
7851 };
7852
7853 let mut orchestrator = EnhancedOrchestrator::new(config, phase_config).unwrap();
7854 let result = orchestrator.generate().unwrap();
7855
7856 assert_eq!(result.statistics.causal_samples_generated, 100);
7858 assert!(result.statistics.causal_validation_passed.is_some());
7860 }
7861
7862 #[test]
7863 fn test_causal_overlay_revenue_cycle_template() {
7864 let mut config = create_test_config();
7865 config.causal.enabled = true;
7866 config.causal.template = "revenue_cycle".to_string();
7867 config.causal.sample_size = 50;
7868 config.causal.validate = false;
7869
7870 let phase_config = PhaseConfig {
7871 generate_master_data: false,
7872 generate_document_flows: false,
7873 generate_journal_entries: true,
7874 inject_anomalies: false,
7875 show_progress: false,
7876 ..Default::default()
7877 };
7878
7879 let mut orchestrator = EnhancedOrchestrator::new(config, phase_config).unwrap();
7880 let result = orchestrator.generate().unwrap();
7881
7882 assert_eq!(result.statistics.causal_samples_generated, 50);
7884 assert!(result.statistics.causal_validation_passed.is_none());
7886 }
7887
7888 #[test]
7889 fn test_all_new_phases_enabled_together() {
7890 let mut config = create_test_config();
7891 config.llm.enabled = true;
7892 config.llm.max_vendor_enrichments = 2;
7893 config.diffusion.enabled = true;
7894 config.diffusion.n_steps = 20;
7895 config.diffusion.sample_size = 10;
7896 config.causal.enabled = true;
7897 config.causal.sample_size = 50;
7898 config.causal.validate = true;
7899
7900 let phase_config = PhaseConfig {
7901 generate_master_data: true,
7902 generate_document_flows: false,
7903 generate_journal_entries: true,
7904 inject_anomalies: false,
7905 show_progress: false,
7906 vendors_per_company: 5,
7907 customers_per_company: 3,
7908 materials_per_company: 3,
7909 assets_per_company: 3,
7910 employees_per_company: 3,
7911 ..Default::default()
7912 };
7913
7914 let mut orchestrator = EnhancedOrchestrator::new(config, phase_config).unwrap();
7915 let result = orchestrator.generate().unwrap();
7916
7917 assert!(result.statistics.llm_vendors_enriched > 0);
7919 assert_eq!(result.statistics.diffusion_samples_generated, 10);
7920 assert_eq!(result.statistics.causal_samples_generated, 50);
7921 assert!(result.statistics.causal_validation_passed.is_some());
7922 }
7923
7924 #[test]
7925 fn test_statistics_serialization_with_new_fields() {
7926 let stats = EnhancedGenerationStatistics {
7927 total_entries: 100,
7928 total_line_items: 500,
7929 llm_enrichment_ms: 42,
7930 llm_vendors_enriched: 10,
7931 diffusion_enhancement_ms: 100,
7932 diffusion_samples_generated: 50,
7933 causal_generation_ms: 200,
7934 causal_samples_generated: 100,
7935 causal_validation_passed: Some(true),
7936 ..Default::default()
7937 };
7938
7939 let json = serde_json::to_string(&stats).unwrap();
7940 let deserialized: EnhancedGenerationStatistics = serde_json::from_str(&json).unwrap();
7941
7942 assert_eq!(deserialized.llm_enrichment_ms, 42);
7943 assert_eq!(deserialized.llm_vendors_enriched, 10);
7944 assert_eq!(deserialized.diffusion_enhancement_ms, 100);
7945 assert_eq!(deserialized.diffusion_samples_generated, 50);
7946 assert_eq!(deserialized.causal_generation_ms, 200);
7947 assert_eq!(deserialized.causal_samples_generated, 100);
7948 assert_eq!(deserialized.causal_validation_passed, Some(true));
7949 }
7950
7951 #[test]
7952 fn test_statistics_backward_compat_deserialization() {
7953 let old_json = r#"{
7955 "total_entries": 100,
7956 "total_line_items": 500,
7957 "accounts_count": 50,
7958 "companies_count": 1,
7959 "period_months": 12,
7960 "vendor_count": 10,
7961 "customer_count": 20,
7962 "material_count": 15,
7963 "asset_count": 5,
7964 "employee_count": 8,
7965 "p2p_chain_count": 5,
7966 "o2c_chain_count": 5,
7967 "ap_invoice_count": 5,
7968 "ar_invoice_count": 5,
7969 "ocpm_event_count": 0,
7970 "ocpm_object_count": 0,
7971 "ocpm_case_count": 0,
7972 "audit_engagement_count": 0,
7973 "audit_workpaper_count": 0,
7974 "audit_evidence_count": 0,
7975 "audit_risk_count": 0,
7976 "audit_finding_count": 0,
7977 "audit_judgment_count": 0,
7978 "anomalies_injected": 0,
7979 "data_quality_issues": 0,
7980 "banking_customer_count": 0,
7981 "banking_account_count": 0,
7982 "banking_transaction_count": 0,
7983 "banking_suspicious_count": 0,
7984 "graph_export_count": 0,
7985 "graph_node_count": 0,
7986 "graph_edge_count": 0
7987 }"#;
7988
7989 let stats: EnhancedGenerationStatistics = serde_json::from_str(old_json).unwrap();
7990
7991 assert_eq!(stats.llm_enrichment_ms, 0);
7993 assert_eq!(stats.llm_vendors_enriched, 0);
7994 assert_eq!(stats.diffusion_enhancement_ms, 0);
7995 assert_eq!(stats.diffusion_samples_generated, 0);
7996 assert_eq!(stats.causal_generation_ms, 0);
7997 assert_eq!(stats.causal_samples_generated, 0);
7998 assert!(stats.causal_validation_passed.is_none());
7999 }
8000}