1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
//! Chart of Accounts structures for GL account management.
//!
//! Defines the hierarchical structure of financial accounts used in
//! the general ledger, including account classifications aligned with
//! standard financial reporting requirements.
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
/// Primary account type classification following standard financial statement structure.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AccountType {
/// Assets - resources owned by the entity
Asset,
/// Liabilities - obligations owed to others
Liability,
/// Equity - residual interest in assets after deducting liabilities
Equity,
/// Revenue - income from operations
Revenue,
/// Expense - costs incurred in operations
Expense,
/// Statistical - non-financial tracking accounts
Statistical,
}
impl AccountType {
/// Returns true if this is a balance sheet account type.
pub fn is_balance_sheet(&self) -> bool {
matches!(self, Self::Asset | Self::Liability | Self::Equity)
}
/// Returns true if this is an income statement account type.
pub fn is_income_statement(&self) -> bool {
matches!(self, Self::Revenue | Self::Expense)
}
/// Returns the normal balance side (true = debit, false = credit).
pub fn normal_debit_balance(&self) -> bool {
matches!(self, Self::Asset | Self::Expense)
}
}
/// Detailed sub-classification for accounts within each type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AccountSubType {
// Assets
/// Cash and cash equivalents
Cash,
/// Trade receivables
AccountsReceivable,
/// Other receivables
OtherReceivables,
/// Raw materials, WIP, finished goods
Inventory,
/// Prepaid expenses and deferred charges
PrepaidExpenses,
/// Property, plant and equipment
FixedAssets,
/// Contra-asset for depreciation
AccumulatedDepreciation,
/// Long-term investments
Investments,
/// Patents, trademarks, goodwill
IntangibleAssets,
/// Miscellaneous assets
OtherAssets,
// Liabilities
/// Trade payables
AccountsPayable,
/// Accrued expenses
AccruedLiabilities,
/// Short-term borrowings
ShortTermDebt,
/// Long-term borrowings
LongTermDebt,
/// Unearned revenue
DeferredRevenue,
/// Current and deferred taxes payable
TaxLiabilities,
/// Pension and other post-employment benefits
PensionLiabilities,
/// Miscellaneous liabilities
OtherLiabilities,
// Equity
/// Par value of shares issued
CommonStock,
/// Accumulated profits
RetainedEarnings,
/// Premium on share issuance
AdditionalPaidInCapital,
/// Repurchased shares
TreasuryStock,
/// Unrealized gains/losses
OtherComprehensiveIncome,
/// Current period profit/loss
NetIncome,
// Revenue
/// Sales of products
ProductRevenue,
/// Sales of services
ServiceRevenue,
/// Interest earned
InterestIncome,
/// Dividends received
DividendIncome,
/// Gains on asset sales
GainOnSale,
/// Miscellaneous income
OtherIncome,
// Expense
/// Direct costs of goods sold
CostOfGoodsSold,
/// General operating expenses
OperatingExpenses,
/// Sales and marketing costs
SellingExpenses,
/// G&A costs
AdministrativeExpenses,
/// Depreciation of fixed assets
DepreciationExpense,
/// Amortization of intangibles
AmortizationExpense,
/// Interest on borrowings
InterestExpense,
/// Income tax expense
TaxExpense,
/// Foreign exchange losses
ForeignExchangeLoss,
/// Losses on asset sales
LossOnSale,
/// Miscellaneous expenses
OtherExpenses,
// Suspense/Clearing
/// Clearing accounts for temporary postings
SuspenseClearing,
/// GR/IR clearing
GoodsReceivedClearing,
/// Bank clearing accounts
BankClearing,
/// Intercompany clearing
IntercompanyClearing,
}
impl AccountSubType {
/// Get the parent account type for this sub-type.
pub fn account_type(&self) -> AccountType {
match self {
Self::Cash
| Self::AccountsReceivable
| Self::OtherReceivables
| Self::Inventory
| Self::PrepaidExpenses
| Self::FixedAssets
| Self::AccumulatedDepreciation
| Self::Investments
| Self::IntangibleAssets
| Self::OtherAssets => AccountType::Asset,
Self::AccountsPayable
| Self::AccruedLiabilities
| Self::ShortTermDebt
| Self::LongTermDebt
| Self::DeferredRevenue
| Self::TaxLiabilities
| Self::PensionLiabilities
| Self::OtherLiabilities => AccountType::Liability,
Self::CommonStock
| Self::RetainedEarnings
| Self::AdditionalPaidInCapital
| Self::TreasuryStock
| Self::OtherComprehensiveIncome
| Self::NetIncome => AccountType::Equity,
Self::ProductRevenue
| Self::ServiceRevenue
| Self::InterestIncome
| Self::DividendIncome
| Self::GainOnSale
| Self::OtherIncome => AccountType::Revenue,
Self::CostOfGoodsSold
| Self::OperatingExpenses
| Self::SellingExpenses
| Self::AdministrativeExpenses
| Self::DepreciationExpense
| Self::AmortizationExpense
| Self::InterestExpense
| Self::TaxExpense
| Self::ForeignExchangeLoss
| Self::LossOnSale
| Self::OtherExpenses => AccountType::Expense,
Self::SuspenseClearing
| Self::GoodsReceivedClearing
| Self::BankClearing
| Self::IntercompanyClearing => AccountType::Asset, // Clearing accounts typically treated as assets
}
}
/// Check if this is a suspense/clearing account type.
pub fn is_suspense(&self) -> bool {
matches!(
self,
Self::SuspenseClearing
| Self::GoodsReceivedClearing
| Self::BankClearing
| Self::IntercompanyClearing
)
}
}
/// Industry sector for account relevance weighting.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum IndustrySector {
#[default]
Manufacturing,
Retail,
FinancialServices,
Healthcare,
Technology,
ProfessionalServices,
Energy,
Transportation,
RealEstate,
Telecommunications,
}
/// Industry relevance weights for account selection during generation.
///
/// Weights from 0.0 to 1.0 indicating how relevant an account is for each industry.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct IndustryWeights {
pub manufacturing: f64,
pub retail: f64,
pub financial_services: f64,
pub healthcare: f64,
pub technology: f64,
pub professional_services: f64,
pub energy: f64,
pub transportation: f64,
pub real_estate: f64,
pub telecommunications: f64,
}
impl IndustryWeights {
/// Create weights where all industries have equal relevance.
pub fn all_equal(weight: f64) -> Self {
Self {
manufacturing: weight,
retail: weight,
financial_services: weight,
healthcare: weight,
technology: weight,
professional_services: weight,
energy: weight,
transportation: weight,
real_estate: weight,
telecommunications: weight,
}
}
/// Get weight for a specific industry.
pub fn get(&self, industry: IndustrySector) -> f64 {
match industry {
IndustrySector::Manufacturing => self.manufacturing,
IndustrySector::Retail => self.retail,
IndustrySector::FinancialServices => self.financial_services,
IndustrySector::Healthcare => self.healthcare,
IndustrySector::Technology => self.technology,
IndustrySector::ProfessionalServices => self.professional_services,
IndustrySector::Energy => self.energy,
IndustrySector::Transportation => self.transportation,
IndustrySector::RealEstate => self.real_estate,
IndustrySector::Telecommunications => self.telecommunications,
}
}
}
/// Individual GL account definition.
///
/// Represents a single account in the chart of accounts with all necessary
/// metadata for realistic transaction generation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GLAccount {
/// Account number (e.g., "100000", "400100")
pub account_number: String,
/// Short description
pub short_description: String,
/// Long description
pub long_description: String,
/// Primary account type
pub account_type: AccountType,
/// Detailed sub-type classification
pub sub_type: AccountSubType,
/// ISO 21378 (Audit Data Collection) Level-2 account class code
/// (e.g. `"A.B"` for Trade Receivables, `"X.A"` for Cost of Goods
/// Sold). Derived from `sub_type` via
/// [`crate::iso21378::from_account_sub_type`]. **v5.6.0 schema
/// change**: prior versions populated this with the first digit of
/// `account_number` (e.g. `"1"`); the new value is the descriptive
/// ISO code consumers can filter / group by directly.
pub account_class: String,
/// ISO 21378 Level-2 account class name (e.g. `"Trade
/// Receivables"`, `"Cost of Goods Sold"`). Added in v5.6.0.
#[serde(default)]
pub account_class_name: String,
/// ISO 21378 Level-3 account sub-class code (e.g. `"A.B.A"` for
/// Trade Accounts Receivable). Added in v5.6.0.
#[serde(default)]
pub account_sub_class: String,
/// ISO 21378 Level-3 account sub-class name (e.g. `"Trade Accounts
/// Receivable"`). Added in v5.6.0.
#[serde(default)]
pub account_sub_class_name: String,
/// Account group for reporting
pub account_group: String,
/// Is this a control account (subledger summary)
pub is_control_account: bool,
/// Is this a suspense/clearing account
pub is_suspense_account: bool,
/// Parent account number (for hierarchies)
pub parent_account: Option<String>,
/// Account hierarchy level (1 = top level)
pub hierarchy_level: u8,
/// Normal balance side (true = debit, false = credit)
pub normal_debit_balance: bool,
/// Is posting allowed directly to this account
pub is_postable: bool,
/// Is this account blocked for posting
pub is_blocked: bool,
/// Allowed document types for this account
pub allowed_doc_types: Vec<String>,
/// Required cost center assignment
pub requires_cost_center: bool,
/// Required profit center assignment
pub requires_profit_center: bool,
/// Industry sector relevance scores (0.0-1.0)
pub industry_weights: IndustryWeights,
/// Typical transaction frequency (transactions per month)
pub typical_frequency: f64,
/// Typical transaction amount range (min, max)
pub typical_amount_range: (f64, f64),
/// Accounting framework this account belongs to (e.g., "us_gaap",
/// "french_pcg", "german_skr04"). Mirrors the parent
/// [`ChartOfAccounts::accounting_framework`] sidecar so per-row
/// consumers (CSV / parquet readers) can filter by framework
/// without joining back to `coa_meta`. Added in v5.0.1.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub accounting_framework: Option<String>,
}
impl GLAccount {
/// Create a new GL account with minimal required fields.
///
/// `account_class`, `account_class_name`, `account_sub_class`,
/// `account_sub_class_name` are auto-derived from `sub_type` via
/// the ISO 21378 mapping in [`crate::iso21378`].
pub fn new(
account_number: String,
description: String,
account_type: AccountType,
sub_type: AccountSubType,
) -> Self {
let adc_sub = crate::iso21378::from_account_sub_type(sub_type);
let adc_class = adc_sub.adc_class();
Self {
account_number,
short_description: description.clone(),
long_description: description,
account_type,
sub_type,
account_class: adc_class.code().to_string(),
account_class_name: adc_class.name().to_string(),
account_sub_class: adc_sub.code().to_string(),
account_sub_class_name: adc_sub.name().to_string(),
account_group: "DEFAULT".to_string(),
is_control_account: false,
is_suspense_account: sub_type.is_suspense(),
parent_account: None,
hierarchy_level: 1,
normal_debit_balance: account_type.normal_debit_balance(),
is_postable: true,
is_blocked: false,
allowed_doc_types: vec!["SA".to_string()],
requires_cost_center: matches!(account_type, AccountType::Expense),
requires_profit_center: false,
industry_weights: IndustryWeights::all_equal(1.0),
typical_frequency: 100.0,
typical_amount_range: (100.0, 100000.0),
accounting_framework: None,
}
}
/// Get account code (alias for account_number).
pub fn account_code(&self) -> &str {
&self.account_number
}
/// Get description (alias for short_description).
pub fn description(&self) -> &str {
&self.short_description
}
}
/// Chart of Accounts complexity levels.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum CoAComplexity {
/// ~100 accounts - small business
#[default]
Small,
/// ~400 accounts - mid-market
Medium,
/// ~2500 accounts - enterprise (based on paper's max observation)
Large,
}
impl CoAComplexity {
/// Get the target account count for this complexity level.
pub fn target_count(&self) -> usize {
match self {
Self::Small => 100,
Self::Medium => 400,
Self::Large => 2500,
}
}
}
/// Complete Chart of Accounts structure.
///
/// Contains all GL accounts for an entity along with metadata about
/// the overall structure.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ChartOfAccounts {
/// Unique identifier for this CoA
pub coa_id: String,
/// Name/description
pub name: String,
/// Country/region code
pub country: String,
/// Industry sector this CoA is designed for
pub industry: IndustrySector,
/// All accounts in this CoA
pub accounts: Vec<GLAccount>,
/// Complexity level
pub complexity: CoAComplexity,
/// Account number format (e.g., "######" for 6 digits)
pub account_format: String,
/// v4.4.1+ accounting framework for this CoA — "us_gaap", "ifrs",
/// "french_gaap", "german_gaap", or "dual_reporting". Populated by
/// the orchestrator from `config.accounting_standards.framework`
/// when `accounting_standards.enabled = true`; `None` otherwise.
/// SDK consumers previously reported this field as null across
/// the board — before v4.4.1 it simply didn't exist.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub accounting_framework: Option<String>,
/// Index by account number for fast lookup
#[serde(skip)]
account_index: HashMap<String, usize>,
}
impl ChartOfAccounts {
/// Create a new empty Chart of Accounts.
pub fn new(
coa_id: String,
name: String,
country: String,
industry: IndustrySector,
complexity: CoAComplexity,
) -> Self {
Self {
coa_id,
name,
country,
industry,
accounts: Vec::new(),
complexity,
account_format: "######".to_string(),
accounting_framework: None,
account_index: HashMap::new(),
}
}
/// v4.4.1+ builder for the accounting framework label (e.g.
/// `"us_gaap"`, `"ifrs"`). Typically invoked by the orchestrator
/// from the parsed `AccountingFrameworkConfig`.
pub fn with_accounting_framework(mut self, framework: impl Into<String>) -> Self {
self.accounting_framework = Some(framework.into());
self
}
/// Add an account to the CoA.
pub fn add_account(&mut self, account: GLAccount) {
let idx = self.accounts.len();
self.account_index
.insert(account.account_number.clone(), idx);
self.accounts.push(account);
}
/// Rebuild the account index (call after deserialization).
pub fn rebuild_index(&mut self) {
self.account_index.clear();
for (idx, account) in self.accounts.iter().enumerate() {
self.account_index
.insert(account.account_number.clone(), idx);
}
}
/// Get an account by number.
pub fn get_account(&self, account_number: &str) -> Option<&GLAccount> {
self.account_index
.get(account_number)
.map(|&idx| &self.accounts[idx])
}
/// Get all postable accounts.
pub fn get_postable_accounts(&self) -> Vec<&GLAccount> {
self.accounts
.iter()
.filter(|a| a.is_postable && !a.is_blocked)
.collect()
}
/// Get all accounts of a specific type.
pub fn get_accounts_by_type(&self, account_type: AccountType) -> Vec<&GLAccount> {
self.accounts
.iter()
.filter(|a| a.account_type == account_type && a.is_postable && !a.is_blocked)
.collect()
}
/// Get all accounts of a specific sub-type.
pub fn get_accounts_by_sub_type(&self, sub_type: AccountSubType) -> Vec<&GLAccount> {
self.accounts
.iter()
.filter(|a| a.sub_type == sub_type && a.is_postable && !a.is_blocked)
.collect()
}
/// Get suspense/clearing accounts.
pub fn get_suspense_accounts(&self) -> Vec<&GLAccount> {
self.accounts
.iter()
.filter(|a| a.is_suspense_account && a.is_postable)
.collect()
}
/// **v5.7.0** — pick a postable sub-account for a parent canonical
/// account, deterministic per `document_id`.
///
/// When the COA was generated with
/// `expand_industry_subaccounts: true`, each canonical parent (e.g.
/// `"4000"`) is non-postable and its real postings target one of
/// its 6-digit sub-accounts (`"400010"`, `"400020"`, …). This
/// helper deterministically selects one of those sub-accounts based
/// on a stable hash of `document_id` and the configured weights:
///
/// 1. If `parent_account` doesn't exist in the COA, returns `None`.
/// 2. If no sub-accounts (children with `parent_account == parent`)
/// exist, returns `parent_account` itself (legacy behaviour —
/// expansion was not enabled or this parent is not in the
/// industry pack).
/// 3. Otherwise hashes `document_id` to a position in the cumulative
/// weight distribution and returns that sub-account number.
///
/// Determinism: the same `(parent_account, document_id)` pair
/// always returns the same sub-account, across regenerations and
/// across platforms.
pub fn pick_subaccount_for_document(
&self,
parent_account: &str,
document_id: uuid::Uuid,
) -> Option<String> {
// 1. Parent must exist.
self.get_account(parent_account)?;
// 2. Collect sub-accounts.
let subs: Vec<&GLAccount> = self
.accounts
.iter()
.filter(|a| {
a.parent_account.as_deref() == Some(parent_account)
&& a.is_postable
&& !a.is_blocked
})
.collect();
if subs.is_empty() {
return Some(parent_account.to_string());
}
// 3. Hash document_id + parent to a u64 (FNV-1a — same family
// used by uuid_factory for determinism).
let mut hash: u64 = 0xcbf29ce484222325;
for byte in document_id.as_bytes() {
hash ^= u64::from(*byte);
hash = hash.wrapping_mul(0x100000001b3);
}
for byte in parent_account.as_bytes() {
hash ^= u64::from(*byte);
hash = hash.wrapping_mul(0x100000001b3);
}
// Default per-sub weight is 1.0 (since GLAccount doesn't carry
// a weight field; the industry pack's weights are applied at
// expansion time by ordering — earlier entries are higher-
// weight, but we don't preserve them on GLAccount).
// For v5.7.0 MVP we use uniform-by-position selection. The
// pack's weight ordering still influences which sub-accounts
// get added (high-weight ones present, low-weight rare).
let idx = (hash as usize) % subs.len();
Some(subs[idx].account_number.clone())
}
/// Get accounts weighted by industry relevance.
pub fn get_industry_weighted_accounts(
&self,
account_type: AccountType,
) -> Vec<(&GLAccount, f64)> {
self.get_accounts_by_type(account_type)
.into_iter()
.map(|a| {
let weight = a.industry_weights.get(self.industry);
(a, weight)
})
.filter(|(_, w)| *w > 0.0)
.collect()
}
/// Get total account count.
pub fn account_count(&self) -> usize {
self.accounts.len()
}
/// Get count of postable accounts.
pub fn postable_count(&self) -> usize {
self.accounts.iter().filter(|a| a.is_postable).count()
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
#[test]
fn test_account_type_balance() {
assert!(AccountType::Asset.normal_debit_balance());
assert!(AccountType::Expense.normal_debit_balance());
assert!(!AccountType::Liability.normal_debit_balance());
assert!(!AccountType::Revenue.normal_debit_balance());
assert!(!AccountType::Equity.normal_debit_balance());
}
#[test]
fn test_coa_complexity_count() {
assert_eq!(CoAComplexity::Small.target_count(), 100);
assert_eq!(CoAComplexity::Medium.target_count(), 400);
assert_eq!(CoAComplexity::Large.target_count(), 2500);
}
#[test]
fn test_coa_account_lookup() {
let mut coa = ChartOfAccounts::new(
"TEST".to_string(),
"Test CoA".to_string(),
"US".to_string(),
IndustrySector::Manufacturing,
CoAComplexity::Small,
);
coa.add_account(GLAccount::new(
"100000".to_string(),
"Cash".to_string(),
AccountType::Asset,
AccountSubType::Cash,
));
assert!(coa.get_account("100000").is_some());
assert!(coa.get_account("999999").is_none());
}
}