rustkernel_accounting/
types.rs

1//! Accounting types.
2
3use serde::{Deserialize, Serialize};
4use std::collections::HashMap;
5
6// ============================================================================
7// Chart of Accounts Types
8// ============================================================================
9
10/// Account in chart of accounts.
11#[derive(Debug, Clone)]
12pub struct Account {
13    /// Account code.
14    pub code: String,
15    /// Account name.
16    pub name: String,
17    /// Account type.
18    pub account_type: AccountType,
19    /// Parent account code (for hierarchy).
20    pub parent_code: Option<String>,
21    /// Is active.
22    pub is_active: bool,
23    /// Currency.
24    pub currency: String,
25    /// Entity ID.
26    pub entity_id: String,
27    /// Attributes.
28    pub attributes: HashMap<String, String>,
29}
30
31/// Account type.
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
33pub enum AccountType {
34    /// Asset account.
35    Asset,
36    /// Liability account.
37    Liability,
38    /// Equity account.
39    Equity,
40    /// Revenue account.
41    Revenue,
42    /// Expense account.
43    Expense,
44    /// Contra account.
45    Contra,
46}
47
48/// Account mapping rule.
49#[derive(Debug, Clone)]
50pub struct MappingRule {
51    /// Rule ID.
52    pub id: String,
53    /// Source account pattern.
54    pub source_pattern: String,
55    /// Target account code.
56    pub target_code: String,
57    /// Entity filter (if any).
58    pub entity_filter: Option<String>,
59    /// Priority (higher = applied first).
60    pub priority: u32,
61    /// Transformation to apply.
62    pub transformation: MappingTransformation,
63}
64
65/// Mapping transformation.
66#[derive(Debug, Clone)]
67pub enum MappingTransformation {
68    /// Direct mapping.
69    Direct,
70    /// Proportional split.
71    Split(Vec<(String, f64)>),
72    /// Aggregation.
73    Aggregate,
74    /// Conditional mapping.
75    Conditional {
76        /// Condition expression to evaluate.
77        condition: String,
78        /// Target account if condition is true.
79        if_true: String,
80        /// Target account if condition is false.
81        if_false: String,
82    },
83}
84
85/// Mapping result.
86#[derive(Debug, Clone)]
87pub struct MappingResult {
88    /// Mapped accounts.
89    pub mapped: Vec<MappedAccount>,
90    /// Unmapped accounts.
91    pub unmapped: Vec<String>,
92    /// Mapping statistics.
93    pub stats: MappingStats,
94}
95
96/// Mapped account.
97#[derive(Debug, Clone)]
98pub struct MappedAccount {
99    /// Source account code.
100    pub source_code: String,
101    /// Target account code.
102    pub target_code: String,
103    /// Applied rule ID.
104    pub rule_id: String,
105    /// Amount (if split).
106    pub amount_ratio: f64,
107}
108
109/// Mapping statistics.
110#[derive(Debug, Clone)]
111pub struct MappingStats {
112    /// Total accounts.
113    pub total_accounts: usize,
114    /// Mapped count.
115    pub mapped_count: usize,
116    /// Unmapped count.
117    pub unmapped_count: usize,
118    /// Rules applied.
119    pub rules_applied: usize,
120    /// Mapping rate.
121    pub mapping_rate: f64,
122}
123
124// ============================================================================
125// Journal Types
126// ============================================================================
127
128/// Journal entry.
129#[derive(Debug, Clone, Serialize, Deserialize)]
130pub struct JournalEntry {
131    /// Entry ID.
132    pub id: u64,
133    /// Entry date.
134    pub date: u64,
135    /// Posting date.
136    pub posting_date: u64,
137    /// Document number.
138    pub document_number: String,
139    /// Lines.
140    pub lines: Vec<JournalLine>,
141    /// Status.
142    pub status: JournalStatus,
143    /// Source system.
144    pub source_system: String,
145    /// Description.
146    pub description: String,
147}
148
149/// Journal line.
150#[derive(Debug, Clone, Serialize, Deserialize)]
151pub struct JournalLine {
152    /// Line number.
153    pub line_number: u32,
154    /// Account code.
155    pub account_code: String,
156    /// Debit amount.
157    pub debit: f64,
158    /// Credit amount.
159    pub credit: f64,
160    /// Currency.
161    pub currency: String,
162    /// Entity ID.
163    pub entity_id: String,
164    /// Cost center.
165    pub cost_center: Option<String>,
166    /// Description.
167    pub description: String,
168}
169
170/// Journal status.
171#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
172pub enum JournalStatus {
173    /// Draft.
174    Draft,
175    /// Pending approval.
176    Pending,
177    /// Posted.
178    Posted,
179    /// Reversed.
180    Reversed,
181}
182
183/// Journal transformation result.
184#[derive(Debug, Clone)]
185pub struct TransformationResult {
186    /// Transformed entries.
187    pub entries: Vec<JournalEntry>,
188    /// Validation errors.
189    pub errors: Vec<ValidationError>,
190    /// Statistics.
191    pub stats: TransformationStats,
192}
193
194/// Validation error.
195#[derive(Debug, Clone)]
196pub struct ValidationError {
197    /// Entry ID.
198    pub entry_id: u64,
199    /// Line number (if applicable).
200    pub line_number: Option<u32>,
201    /// Error code.
202    pub code: String,
203    /// Error message.
204    pub message: String,
205    /// Severity.
206    pub severity: ErrorSeverity,
207}
208
209/// Error severity.
210#[derive(Debug, Clone, Copy, PartialEq, Eq)]
211pub enum ErrorSeverity {
212    /// Warning.
213    Warning,
214    /// Error.
215    Error,
216    /// Critical.
217    Critical,
218}
219
220/// Transformation statistics.
221#[derive(Debug, Clone)]
222pub struct TransformationStats {
223    /// Total entries.
224    pub total_entries: usize,
225    /// Transformed count.
226    pub transformed_count: usize,
227    /// Error count.
228    pub error_count: usize,
229    /// Total debit.
230    pub total_debit: f64,
231    /// Total credit.
232    pub total_credit: f64,
233}
234
235// ============================================================================
236// Reconciliation Types
237// ============================================================================
238
239/// Reconciliation item.
240#[derive(Debug, Clone)]
241pub struct ReconciliationItem {
242    /// Item ID.
243    pub id: String,
244    /// Source.
245    pub source: ReconciliationSource,
246    /// Account code.
247    pub account_code: String,
248    /// Amount.
249    pub amount: f64,
250    /// Currency.
251    pub currency: String,
252    /// Date.
253    pub date: u64,
254    /// Reference.
255    pub reference: String,
256    /// Status.
257    pub status: ReconciliationStatus,
258    /// Matched item ID (if matched).
259    pub matched_with: Option<String>,
260}
261
262/// Reconciliation source.
263#[derive(Debug, Clone, Copy, PartialEq, Eq)]
264pub enum ReconciliationSource {
265    /// General ledger.
266    GeneralLedger,
267    /// Sub-ledger.
268    SubLedger,
269    /// Bank statement.
270    BankStatement,
271    /// External system.
272    External,
273}
274
275/// Reconciliation status.
276#[derive(Debug, Clone, Copy, PartialEq, Eq)]
277pub enum ReconciliationStatus {
278    /// Unmatched.
279    Unmatched,
280    /// Matched.
281    Matched,
282    /// Partially matched.
283    PartiallyMatched,
284    /// Exception.
285    Exception,
286}
287
288/// Reconciliation result.
289#[derive(Debug, Clone)]
290pub struct ReconciliationResult {
291    /// Matched pairs.
292    pub matched_pairs: Vec<MatchedPair>,
293    /// Unmatched items.
294    pub unmatched: Vec<String>,
295    /// Exceptions.
296    pub exceptions: Vec<ReconciliationException>,
297    /// Statistics.
298    pub stats: ReconciliationStats,
299}
300
301/// Matched pair.
302#[derive(Debug, Clone)]
303pub struct MatchedPair {
304    /// Source item ID.
305    pub source_id: String,
306    /// Target item ID.
307    pub target_id: String,
308    /// Match confidence.
309    pub confidence: f64,
310    /// Variance (if any).
311    pub variance: f64,
312    /// Match type.
313    pub match_type: MatchType,
314}
315
316/// Match type.
317#[derive(Debug, Clone, Copy, PartialEq, Eq)]
318pub enum MatchType {
319    /// Exact match.
320    Exact,
321    /// Tolerance match.
322    Tolerance,
323    /// Many to one.
324    ManyToOne,
325    /// One to many.
326    OneToMany,
327    /// Many to many.
328    ManyToMany,
329}
330
331/// Reconciliation exception.
332#[derive(Debug, Clone)]
333pub struct ReconciliationException {
334    /// Item ID.
335    pub item_id: String,
336    /// Exception type.
337    pub exception_type: ExceptionType,
338    /// Description.
339    pub description: String,
340    /// Suggested action.
341    pub suggested_action: Option<String>,
342}
343
344/// Exception type.
345#[derive(Debug, Clone, Copy, PartialEq, Eq)]
346pub enum ExceptionType {
347    /// Amount variance.
348    AmountVariance,
349    /// Date variance.
350    DateVariance,
351    /// Missing counterpart.
352    MissingCounterpart,
353    /// Duplicate.
354    Duplicate,
355    /// Other.
356    Other,
357}
358
359/// Reconciliation statistics.
360#[derive(Debug, Clone)]
361pub struct ReconciliationStats {
362    /// Total items.
363    pub total_items: usize,
364    /// Matched count.
365    pub matched_count: usize,
366    /// Unmatched count.
367    pub unmatched_count: usize,
368    /// Exception count.
369    pub exception_count: usize,
370    /// Match rate.
371    pub match_rate: f64,
372    /// Total variance.
373    pub total_variance: f64,
374}
375
376// ============================================================================
377// Network Analysis Types
378// ============================================================================
379
380/// Intercompany transaction.
381#[derive(Debug, Clone)]
382pub struct IntercompanyTransaction {
383    /// Transaction ID.
384    pub id: String,
385    /// From entity.
386    pub from_entity: String,
387    /// To entity.
388    pub to_entity: String,
389    /// Amount.
390    pub amount: f64,
391    /// Currency.
392    pub currency: String,
393    /// Date.
394    pub date: u64,
395    /// Transaction type.
396    pub transaction_type: IntercompanyType,
397    /// Status.
398    pub status: IntercompanyStatus,
399}
400
401/// Intercompany transaction type.
402#[derive(Debug, Clone, Copy, PartialEq, Eq)]
403pub enum IntercompanyType {
404    /// Trade receivable/payable.
405    Trade,
406    /// Loan.
407    Loan,
408    /// Dividend.
409    Dividend,
410    /// Management fee.
411    ManagementFee,
412    /// Royalty.
413    Royalty,
414    /// Other.
415    Other,
416}
417
418/// Intercompany status.
419#[derive(Debug, Clone, Copy, PartialEq, Eq)]
420pub enum IntercompanyStatus {
421    /// Open.
422    Open,
423    /// Confirmed.
424    Confirmed,
425    /// Eliminated.
426    Eliminated,
427    /// Disputed.
428    Disputed,
429}
430
431/// Network analysis result.
432#[derive(Debug, Clone)]
433pub struct NetworkAnalysisResult {
434    /// Entity balances.
435    pub entity_balances: HashMap<String, EntityBalance>,
436    /// Relationship strengths.
437    pub relationships: Vec<EntityRelationship>,
438    /// Circular references.
439    pub circular_refs: Vec<CircularReference>,
440    /// Elimination entries.
441    pub elimination_entries: Vec<EliminationEntry>,
442    /// Statistics.
443    pub stats: NetworkStats,
444}
445
446/// Entity balance.
447#[derive(Debug, Clone)]
448pub struct EntityBalance {
449    /// Entity ID.
450    pub entity_id: String,
451    /// Total intercompany receivables.
452    pub total_receivables: f64,
453    /// Total intercompany payables.
454    pub total_payables: f64,
455    /// Net position.
456    pub net_position: f64,
457    /// Counterparty count.
458    pub counterparty_count: usize,
459}
460
461/// Entity relationship.
462#[derive(Debug, Clone)]
463pub struct EntityRelationship {
464    /// From entity.
465    pub from_entity: String,
466    /// To entity.
467    pub to_entity: String,
468    /// Total volume.
469    pub total_volume: f64,
470    /// Transaction count.
471    pub transaction_count: usize,
472    /// Net balance.
473    pub net_balance: f64,
474}
475
476/// Circular reference.
477#[derive(Debug, Clone)]
478pub struct CircularReference {
479    /// Entities in the circle.
480    pub entities: Vec<String>,
481    /// Total amount.
482    pub amount: f64,
483    /// Impact on consolidation.
484    pub consolidation_impact: f64,
485}
486
487/// Elimination entry.
488#[derive(Debug, Clone)]
489pub struct EliminationEntry {
490    /// Entry ID.
491    pub id: String,
492    /// From entity.
493    pub from_entity: String,
494    /// To entity.
495    pub to_entity: String,
496    /// Debit account.
497    pub debit_account: String,
498    /// Credit account.
499    pub credit_account: String,
500    /// Amount.
501    pub amount: f64,
502    /// Currency.
503    pub currency: String,
504}
505
506/// Network statistics.
507#[derive(Debug, Clone)]
508pub struct NetworkStats {
509    /// Total entities.
510    pub total_entities: usize,
511    /// Total transactions.
512    pub total_transactions: usize,
513    /// Total volume.
514    pub total_volume: f64,
515    /// Circular reference count.
516    pub circular_count: usize,
517    /// Elimination count.
518    pub elimination_count: usize,
519}
520
521// ============================================================================
522// Temporal Correlation Types
523// ============================================================================
524
525/// Account time series.
526#[derive(Debug, Clone)]
527pub struct AccountTimeSeries {
528    /// Account code.
529    pub account_code: String,
530    /// Data points.
531    pub data_points: Vec<TimeSeriesPoint>,
532    /// Frequency.
533    pub frequency: TimeFrequency,
534}
535
536/// Time series point.
537#[derive(Debug, Clone)]
538pub struct TimeSeriesPoint {
539    /// Date.
540    pub date: u64,
541    /// Balance.
542    pub balance: f64,
543    /// Period change.
544    pub period_change: f64,
545}
546
547/// Time frequency.
548#[derive(Debug, Clone, Copy, PartialEq, Eq)]
549pub enum TimeFrequency {
550    /// Daily.
551    Daily,
552    /// Weekly.
553    Weekly,
554    /// Monthly.
555    Monthly,
556    /// Quarterly.
557    Quarterly,
558    /// Annual.
559    Annual,
560}
561
562/// Correlation result.
563#[derive(Debug, Clone)]
564pub struct CorrelationResult {
565    /// Correlation matrix.
566    pub correlations: Vec<AccountCorrelation>,
567    /// Anomalies.
568    pub anomalies: Vec<CorrelationAnomaly>,
569    /// Statistics.
570    pub stats: CorrelationStats,
571}
572
573/// Account correlation.
574#[derive(Debug, Clone)]
575pub struct AccountCorrelation {
576    /// First account.
577    pub account_a: String,
578    /// Second account.
579    pub account_b: String,
580    /// Correlation coefficient.
581    pub coefficient: f64,
582    /// P-value.
583    pub p_value: f64,
584    /// Correlation type.
585    pub correlation_type: CorrelationType,
586}
587
588/// Correlation type.
589#[derive(Debug, Clone, Copy, PartialEq, Eq)]
590pub enum CorrelationType {
591    /// Positive correlation.
592    Positive,
593    /// Negative correlation.
594    Negative,
595    /// No significant correlation.
596    None,
597}
598
599/// Correlation anomaly.
600#[derive(Debug, Clone)]
601pub struct CorrelationAnomaly {
602    /// Account code.
603    pub account_code: String,
604    /// Date.
605    pub date: u64,
606    /// Expected value.
607    pub expected: f64,
608    /// Actual value.
609    pub actual: f64,
610    /// Z-score.
611    pub z_score: f64,
612    /// Anomaly type.
613    pub anomaly_type: AnomalyType,
614}
615
616/// Anomaly type.
617#[derive(Debug, Clone, Copy, PartialEq, Eq)]
618pub enum AnomalyType {
619    /// Unexpectedly high.
620    UnexpectedHigh,
621    /// Unexpectedly low.
622    UnexpectedLow,
623    /// Pattern break.
624    PatternBreak,
625    /// Missing expected correlation.
626    MissingCorrelation,
627}
628
629/// Correlation statistics.
630#[derive(Debug, Clone)]
631pub struct CorrelationStats {
632    /// Total accounts analyzed.
633    pub accounts_analyzed: usize,
634    /// Significant correlations.
635    pub significant_correlations: usize,
636    /// Anomaly count.
637    pub anomaly_count: usize,
638    /// Average correlation strength.
639    pub avg_correlation: f64,
640}
641
642// ============================================================================
643// Suspense Account Detection Types
644// ============================================================================
645
646/// Suspense account candidate.
647#[derive(Debug, Clone)]
648pub struct SuspenseAccountCandidate {
649    /// Account code.
650    pub account_code: String,
651    /// Account name.
652    pub account_name: String,
653    /// Suspense score (0-100).
654    pub suspense_score: f64,
655    /// Centrality score (betweenness).
656    pub centrality_score: f64,
657    /// Turnover volume.
658    pub turnover_volume: f64,
659    /// Average holding period (days).
660    pub avg_holding_period: f64,
661    /// Number of unique counterparties.
662    pub counterparty_count: usize,
663    /// In/out balance ratio (1.0 = perfectly balanced).
664    pub balance_ratio: f64,
665    /// Risk level.
666    pub risk_level: SuspenseRiskLevel,
667    /// Indicators that triggered detection.
668    pub indicators: Vec<SuspenseIndicator>,
669}
670
671/// Risk level for suspense accounts.
672#[derive(Debug, Clone, Copy, PartialEq, Eq)]
673pub enum SuspenseRiskLevel {
674    /// Low risk - likely legitimate clearing account.
675    Low,
676    /// Medium risk - needs review.
677    Medium,
678    /// High risk - strong suspense characteristics.
679    High,
680    /// Critical - definite suspense account behavior.
681    Critical,
682}
683
684/// Suspense account indicator.
685#[derive(Debug, Clone, Copy, PartialEq, Eq)]
686pub enum SuspenseIndicator {
687    /// High betweenness centrality.
688    HighCentrality,
689    /// High turnover relative to balance.
690    HighTurnover,
691    /// Short average holding period.
692    ShortHoldingPeriod,
693    /// Balanced in/out flows.
694    BalancedFlows,
695    /// Many counterparties.
696    ManyCounterparties,
697    /// Zero or near-zero period-end balance.
698    ZeroEndBalance,
699    /// Name contains suspense keywords.
700    SuspenseNaming,
701}
702
703/// Suspense account detection result.
704#[derive(Debug, Clone)]
705pub struct SuspenseAccountResult {
706    /// Detected suspense account candidates.
707    pub candidates: Vec<SuspenseAccountCandidate>,
708    /// High-risk accounts.
709    pub high_risk_accounts: Vec<String>,
710    /// Total accounts analyzed.
711    pub accounts_analyzed: usize,
712    /// Overall risk score.
713    pub risk_score: f64,
714}
715
716// ============================================================================
717// GAAP Violation Detection Types
718// ============================================================================
719
720/// GAAP violation.
721#[derive(Debug, Clone)]
722pub struct GaapViolation {
723    /// Violation ID.
724    pub id: String,
725    /// Violation type.
726    pub violation_type: GaapViolationType,
727    /// Involved accounts.
728    pub accounts: Vec<String>,
729    /// Involved transactions/entries.
730    pub entry_ids: Vec<u64>,
731    /// Amount involved.
732    pub amount: f64,
733    /// Description.
734    pub description: String,
735    /// Severity.
736    pub severity: GaapViolationSeverity,
737    /// Suggested remediation.
738    pub remediation: String,
739}
740
741/// Type of GAAP violation.
742#[derive(Debug, Clone, Copy, PartialEq, Eq)]
743pub enum GaapViolationType {
744    /// Direct revenue-to-expense transfer (should go through capital).
745    DirectRevenueExpense,
746    /// Circular flow that inflates revenue.
747    RevenueInflation,
748    /// Off-balance-sheet transaction.
749    OffBalanceSheet,
750    /// Improper intercompany elimination.
751    ImproperElimination,
752    /// Asset-to-expense without depreciation.
753    ImproperAssetExpense,
754    /// Revenue recognition timing violation.
755    RevenueRecognitionTiming,
756    /// Liability understatement.
757    LiabilityUnderstatement,
758    /// Prohibited related-party transaction.
759    ProhibitedRelatedParty,
760    /// Suspense account misuse.
761    SuspenseAccountMisuse,
762}
763
764/// Severity of GAAP violation.
765#[derive(Debug, Clone, Copy, PartialEq, Eq)]
766pub enum GaapViolationSeverity {
767    /// Minor - procedural issue.
768    Minor,
769    /// Moderate - needs correction.
770    Moderate,
771    /// Major - material misstatement.
772    Major,
773    /// Critical - potential fraud indicator.
774    Critical,
775}
776
777/// GAAP violation detection result.
778#[derive(Debug, Clone)]
779pub struct GaapViolationResult {
780    /// Detected violations.
781    pub violations: Vec<GaapViolation>,
782    /// Total entries analyzed.
783    pub entries_analyzed: usize,
784    /// Total amount at risk.
785    pub amount_at_risk: f64,
786    /// Overall compliance score (0-100, higher is better).
787    pub compliance_score: f64,
788    /// Violation counts by type.
789    pub violation_counts: std::collections::HashMap<String, usize>,
790}