datasynth-core 2.4.0

Core domain models, traits, and distributions for synthetic enterprise data generation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
//! Tax accounting data models.
//!
//! This module provides comprehensive tax data models including:
//! - Tax jurisdictions (federal, state, local, municipal, supranational)
//! - Tax codes with rates and effective date ranges
//! - Tax lines attached to source documents (invoices, JEs, payments)
//! - Tax returns (VAT, income tax, withholding remittance, payroll)
//! - Tax provisions under ASC 740 / IAS 12
//! - Uncertain tax positions under FIN 48 / IFRIC 23
//! - Withholding tax records with treaty benefit tracking

use std::collections::HashMap;

use chrono::NaiveDate;
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};

use super::graph_properties::{GraphPropertyValue, ToNodeProperties};

// ---------------------------------------------------------------------------
// Enums
// ---------------------------------------------------------------------------

/// Classification of a tax jurisdiction within a governmental hierarchy.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum JurisdictionType {
    /// National / federal level (e.g., IRS, HMRC)
    #[default]
    Federal,
    /// State / province level
    State,
    /// County / city level
    Local,
    /// Municipal / district level
    Municipal,
    /// Supranational body (e.g., EU VAT)
    Supranational,
}

/// High-level classification of a tax.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum TaxType {
    /// Value Added Tax
    #[default]
    Vat,
    /// Goods and Services Tax
    Gst,
    /// Sales Tax (destination-based)
    SalesTax,
    /// Corporate / individual income tax
    IncomeTax,
    /// Withholding tax on cross-border payments
    WithholdingTax,
    /// Employer / employee payroll taxes
    PayrollTax,
    /// Excise / duty taxes
    ExciseTax,
}

/// The type of source document a tax line is attached to.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum TaxableDocumentType {
    /// Accounts-payable vendor invoice
    #[default]
    VendorInvoice,
    /// Accounts-receivable customer invoice
    CustomerInvoice,
    /// Manual journal entry
    JournalEntry,
    /// Cash disbursement / receipt
    Payment,
    /// Payroll run
    PayrollRun,
}

/// Type of periodic tax return filed with an authority.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum TaxReturnType {
    /// VAT / GST return
    #[default]
    VatReturn,
    /// Corporate income tax return
    IncomeTax,
    /// Withholding tax remittance
    WithholdingRemittance,
    /// Payroll tax return
    PayrollTax,
}

/// Lifecycle status of a tax return.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum TaxReturnStatus {
    /// Return is being prepared
    #[default]
    Draft,
    /// Return has been submitted to the authority
    Filed,
    /// Authority has reviewed and issued assessment
    Assessed,
    /// Tax liability has been settled
    Paid,
    /// An amendment has been filed
    Amended,
}

/// Category of withholding tax applied to a payment.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum WithholdingType {
    /// Withholding on dividend distributions
    DividendWithholding,
    /// Withholding on royalty payments
    RoyaltyWithholding,
    /// Withholding on service fees
    #[default]
    ServiceWithholding,
}

/// Measurement method for uncertain tax positions (FIN 48 / IFRIC 23).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum TaxMeasurementMethod {
    /// Single most-likely outcome
    #[default]
    MostLikelyAmount,
    /// Probability-weighted expected value
    ExpectedValue,
}

// ---------------------------------------------------------------------------
// Structs
// ---------------------------------------------------------------------------

/// A taxing authority at a specific level of government.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaxJurisdiction {
    /// Unique jurisdiction identifier
    pub id: String,
    /// Human-readable name (e.g., "United States - Federal")
    pub name: String,
    /// ISO 3166-1 alpha-2 country code
    pub country_code: String,
    /// State / province / region code (ISO 3166-2 subdivision)
    pub region_code: Option<String>,
    /// Tier within the governmental hierarchy
    pub jurisdiction_type: JurisdictionType,
    /// Parent jurisdiction (e.g., state's parent is the federal jurisdiction)
    pub parent_jurisdiction_id: Option<String>,
    /// Whether the entity is VAT-registered in this jurisdiction
    pub vat_registered: bool,
}

impl TaxJurisdiction {
    /// Creates a new tax jurisdiction.
    pub fn new(
        id: impl Into<String>,
        name: impl Into<String>,
        country_code: impl Into<String>,
        jurisdiction_type: JurisdictionType,
    ) -> Self {
        Self {
            id: id.into(),
            name: name.into(),
            country_code: country_code.into(),
            region_code: None,
            jurisdiction_type,
            parent_jurisdiction_id: None,
            vat_registered: false,
        }
    }

    /// Sets the region code.
    pub fn with_region_code(mut self, region_code: impl Into<String>) -> Self {
        self.region_code = Some(region_code.into());
        self
    }

    /// Sets the parent jurisdiction ID.
    pub fn with_parent_jurisdiction_id(mut self, parent_id: impl Into<String>) -> Self {
        self.parent_jurisdiction_id = Some(parent_id.into());
        self
    }

    /// Sets the VAT registration flag.
    pub fn with_vat_registered(mut self, registered: bool) -> Self {
        self.vat_registered = registered;
        self
    }

    /// Returns `true` if the jurisdiction is sub-national (state, local, or municipal).
    pub fn is_subnational(&self) -> bool {
        matches!(
            self.jurisdiction_type,
            JurisdictionType::State | JurisdictionType::Local | JurisdictionType::Municipal
        )
    }
}

/// A tax code defining a rate for a specific tax type and jurisdiction.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaxCode {
    /// Unique tax code identifier
    pub id: String,
    /// Short mnemonic (e.g., "VAT-STD-20", "WHT-SVC-15")
    pub code: String,
    /// Human-readable description
    pub description: String,
    /// Category of tax
    pub tax_type: TaxType,
    /// Tax rate as a decimal fraction (e.g., 0.20 for 20%)
    #[serde(with = "crate::serde_decimal")]
    pub rate: Decimal,
    /// Jurisdiction this code applies to
    pub jurisdiction_id: String,
    /// Date from which the code is effective (inclusive)
    pub effective_date: NaiveDate,
    /// Date after which the code is no longer effective (exclusive)
    pub expiry_date: Option<NaiveDate>,
    /// Whether the reverse-charge mechanism applies
    pub is_reverse_charge: bool,
    /// Whether transactions under this code are tax-exempt
    pub is_exempt: bool,
}

impl TaxCode {
    /// Creates a new tax code.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        id: impl Into<String>,
        code: impl Into<String>,
        description: impl Into<String>,
        tax_type: TaxType,
        rate: Decimal,
        jurisdiction_id: impl Into<String>,
        effective_date: NaiveDate,
    ) -> Self {
        Self {
            id: id.into(),
            code: code.into(),
            description: description.into(),
            tax_type,
            rate,
            jurisdiction_id: jurisdiction_id.into(),
            effective_date,
            expiry_date: None,
            is_reverse_charge: false,
            is_exempt: false,
        }
    }

    /// Sets the expiry date.
    pub fn with_expiry_date(mut self, expiry: NaiveDate) -> Self {
        self.expiry_date = Some(expiry);
        self
    }

    /// Sets the reverse-charge flag.
    pub fn with_reverse_charge(mut self, reverse_charge: bool) -> Self {
        self.is_reverse_charge = reverse_charge;
        self
    }

    /// Sets the exempt flag.
    pub fn with_exempt(mut self, exempt: bool) -> Self {
        self.is_exempt = exempt;
        self
    }

    /// Computes the tax amount for a given taxable base.
    ///
    /// Returns `taxable_amount * rate`, rounded to 2 decimal places.
    /// Exempt codes always return zero.
    pub fn tax_amount(&self, taxable_amount: Decimal) -> Decimal {
        if self.is_exempt {
            return Decimal::ZERO;
        }
        (taxable_amount * self.rate).round_dp(2)
    }

    /// Returns `true` if the tax code is active on the given `date`.
    ///
    /// A code is active when `effective_date <= date` and either no expiry
    /// is set or `date < expiry_date`.
    pub fn is_active(&self, date: NaiveDate) -> bool {
        if date < self.effective_date {
            return false;
        }
        match self.expiry_date {
            Some(expiry) => date < expiry,
            None => true,
        }
    }
}

/// A single tax line attached to a source document.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaxLine {
    /// Unique tax line identifier
    pub id: String,
    /// Type of the source document
    pub document_type: TaxableDocumentType,
    /// Source document identifier
    pub document_id: String,
    /// Line number within the document
    pub line_number: u32,
    /// Tax code applied
    pub tax_code_id: String,
    /// Jurisdiction the tax is assessed in
    pub jurisdiction_id: String,
    /// Base amount subject to tax
    #[serde(with = "crate::serde_decimal")]
    pub taxable_amount: Decimal,
    /// Computed tax amount
    #[serde(with = "crate::serde_decimal")]
    pub tax_amount: Decimal,
    /// Whether the input tax is deductible (reclaimable)
    pub is_deductible: bool,
    /// Whether the reverse-charge mechanism applies
    pub is_reverse_charge: bool,
    /// Whether the tax was self-assessed by the buyer
    pub is_self_assessed: bool,
}

impl TaxLine {
    /// Creates a new tax line.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        id: impl Into<String>,
        document_type: TaxableDocumentType,
        document_id: impl Into<String>,
        line_number: u32,
        tax_code_id: impl Into<String>,
        jurisdiction_id: impl Into<String>,
        taxable_amount: Decimal,
        tax_amount: Decimal,
    ) -> Self {
        Self {
            id: id.into(),
            document_type,
            document_id: document_id.into(),
            line_number,
            tax_code_id: tax_code_id.into(),
            jurisdiction_id: jurisdiction_id.into(),
            taxable_amount,
            tax_amount,
            is_deductible: true,
            is_reverse_charge: false,
            is_self_assessed: false,
        }
    }

    /// Sets the deductible flag.
    pub fn with_deductible(mut self, deductible: bool) -> Self {
        self.is_deductible = deductible;
        self
    }

    /// Sets the reverse-charge flag.
    pub fn with_reverse_charge(mut self, reverse_charge: bool) -> Self {
        self.is_reverse_charge = reverse_charge;
        self
    }

    /// Sets the self-assessed flag.
    pub fn with_self_assessed(mut self, self_assessed: bool) -> Self {
        self.is_self_assessed = self_assessed;
        self
    }

    /// Computes the effective tax rate for this line.
    ///
    /// Returns `tax_amount / taxable_amount`, or `Decimal::ZERO` when the
    /// taxable amount is zero (avoids division by zero).
    pub fn effective_rate(&self) -> Decimal {
        if self.taxable_amount.is_zero() {
            Decimal::ZERO
        } else {
            (self.tax_amount / self.taxable_amount).round_dp(6)
        }
    }
}

/// A periodic tax return filed with a jurisdiction.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaxReturn {
    /// Unique return identifier
    pub id: String,
    /// Legal entity filing the return
    pub entity_id: String,
    /// Jurisdiction the return is filed with
    pub jurisdiction_id: String,
    /// Start of the reporting period
    pub period_start: NaiveDate,
    /// End of the reporting period
    pub period_end: NaiveDate,
    /// Type of return
    pub return_type: TaxReturnType,
    /// Current lifecycle status
    pub status: TaxReturnStatus,
    /// Total output tax (tax collected / charged)
    #[serde(with = "crate::serde_decimal")]
    pub total_output_tax: Decimal,
    /// Total input tax (tax paid / reclaimable)
    #[serde(with = "crate::serde_decimal")]
    pub total_input_tax: Decimal,
    /// Net amount payable to the authority (output - input)
    #[serde(with = "crate::serde_decimal")]
    pub net_payable: Decimal,
    /// Statutory filing deadline
    pub filing_deadline: NaiveDate,
    /// Actual date the return was submitted
    pub actual_filing_date: Option<NaiveDate>,
    /// Whether the return was filed after the deadline
    pub is_late: bool,
}

impl TaxReturn {
    /// Creates a new tax return.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        id: impl Into<String>,
        entity_id: impl Into<String>,
        jurisdiction_id: impl Into<String>,
        period_start: NaiveDate,
        period_end: NaiveDate,
        return_type: TaxReturnType,
        total_output_tax: Decimal,
        total_input_tax: Decimal,
        filing_deadline: NaiveDate,
    ) -> Self {
        let net_payable = (total_output_tax - total_input_tax).round_dp(2);
        Self {
            id: id.into(),
            entity_id: entity_id.into(),
            jurisdiction_id: jurisdiction_id.into(),
            period_start,
            period_end,
            return_type,
            status: TaxReturnStatus::Draft,
            total_output_tax,
            total_input_tax,
            net_payable,
            filing_deadline,
            actual_filing_date: None,
            is_late: false,
        }
    }

    /// Records the actual filing date and derives lateness.
    pub fn with_filing(mut self, filing_date: NaiveDate) -> Self {
        self.actual_filing_date = Some(filing_date);
        self.is_late = filing_date > self.filing_deadline;
        self.status = TaxReturnStatus::Filed;
        self
    }

    /// Sets the return status.
    pub fn with_status(mut self, status: TaxReturnStatus) -> Self {
        self.status = status;
        self
    }

    /// Returns `true` if the return has been submitted (Filed, Assessed, or Paid).
    pub fn is_filed(&self) -> bool {
        matches!(
            self.status,
            TaxReturnStatus::Filed | TaxReturnStatus::Assessed | TaxReturnStatus::Paid
        )
    }
}

/// An item in the statutory-to-effective rate reconciliation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RateReconciliationItem {
    /// Description of the reconciling item (e.g., "State taxes", "R&D credits")
    pub description: String,
    /// Impact on the effective rate (positive increases, negative decreases)
    #[serde(with = "crate::serde_decimal")]
    pub rate_impact: Decimal,
}

/// Income tax provision computed under ASC 740 / IAS 12.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaxProvision {
    /// Unique provision identifier
    pub id: String,
    /// Legal entity the provision relates to
    pub entity_id: String,
    /// Period end date
    pub period: NaiveDate,
    /// Current period income tax expense
    #[serde(with = "crate::serde_decimal")]
    pub current_tax_expense: Decimal,
    /// Deferred tax asset balance
    #[serde(with = "crate::serde_decimal")]
    pub deferred_tax_asset: Decimal,
    /// Deferred tax liability balance
    #[serde(with = "crate::serde_decimal")]
    pub deferred_tax_liability: Decimal,
    /// Statutory tax rate
    #[serde(with = "crate::serde_decimal")]
    pub statutory_rate: Decimal,
    /// Effective tax rate after permanent and temporary differences
    #[serde(with = "crate::serde_decimal")]
    pub effective_rate: Decimal,
    /// Rate reconciliation from statutory to effective rate
    pub rate_reconciliation: Vec<RateReconciliationItem>,
}

impl TaxProvision {
    /// Creates a new tax provision.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        id: impl Into<String>,
        entity_id: impl Into<String>,
        period: NaiveDate,
        current_tax_expense: Decimal,
        deferred_tax_asset: Decimal,
        deferred_tax_liability: Decimal,
        statutory_rate: Decimal,
        effective_rate: Decimal,
    ) -> Self {
        Self {
            id: id.into(),
            entity_id: entity_id.into(),
            period,
            current_tax_expense,
            deferred_tax_asset,
            deferred_tax_liability,
            statutory_rate,
            effective_rate,
            rate_reconciliation: Vec::new(),
        }
    }

    /// Adds a rate reconciliation item.
    pub fn with_reconciliation_item(
        mut self,
        description: impl Into<String>,
        rate_impact: Decimal,
    ) -> Self {
        self.rate_reconciliation.push(RateReconciliationItem {
            description: description.into(),
            rate_impact,
        });
        self
    }

    /// Computes the net deferred tax position.
    ///
    /// Positive value indicates a net deferred tax asset; negative indicates
    /// a net deferred tax liability.
    pub fn net_deferred_tax(&self) -> Decimal {
        self.deferred_tax_asset - self.deferred_tax_liability
    }
}

/// An uncertain tax position evaluated under FIN 48 / IFRIC 23.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UncertainTaxPosition {
    /// Unique UTP identifier
    pub id: String,
    /// Legal entity
    pub entity_id: String,
    /// Description of the tax position
    pub description: String,
    /// Total gross tax benefit claimed
    #[serde(with = "crate::serde_decimal")]
    pub tax_benefit: Decimal,
    /// Recognition threshold (typically 0.50 for "more-likely-than-not")
    #[serde(with = "crate::serde_decimal")]
    pub recognition_threshold: Decimal,
    /// Amount recognized in the financial statements
    #[serde(with = "crate::serde_decimal")]
    pub recognized_amount: Decimal,
    /// Measurement method used to determine the recognized amount
    pub measurement_method: TaxMeasurementMethod,
}

impl UncertainTaxPosition {
    /// Creates a new uncertain tax position.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        id: impl Into<String>,
        entity_id: impl Into<String>,
        description: impl Into<String>,
        tax_benefit: Decimal,
        recognition_threshold: Decimal,
        recognized_amount: Decimal,
        measurement_method: TaxMeasurementMethod,
    ) -> Self {
        Self {
            id: id.into(),
            entity_id: entity_id.into(),
            description: description.into(),
            tax_benefit,
            recognition_threshold,
            recognized_amount,
            measurement_method,
        }
    }

    /// Returns the portion of the tax benefit that has **not** been recognized.
    pub fn unrecognized_amount(&self) -> Decimal {
        self.tax_benefit - self.recognized_amount
    }
}

/// A withholding tax record associated with a cross-border payment.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WithholdingTaxRecord {
    /// Unique record identifier
    pub id: String,
    /// Payment document this withholding relates to
    pub payment_id: String,
    /// Vendor / payee subject to withholding
    pub vendor_id: String,
    /// Category of withholding
    pub withholding_type: WithholdingType,
    /// Reduced rate under an applicable tax treaty
    #[serde(default, with = "crate::serde_decimal::option")]
    pub treaty_rate: Option<Decimal>,
    /// Domestic statutory withholding rate
    #[serde(with = "crate::serde_decimal")]
    pub statutory_rate: Decimal,
    /// Rate actually applied (may equal treaty_rate or statutory_rate)
    #[serde(with = "crate::serde_decimal")]
    pub applied_rate: Decimal,
    /// Gross payment amount subject to withholding
    #[serde(with = "crate::serde_decimal")]
    pub base_amount: Decimal,
    /// Amount withheld (base_amount * applied_rate)
    #[serde(with = "crate::serde_decimal")]
    pub withheld_amount: Decimal,
    /// Tax certificate / receipt number from the authority
    pub certificate_number: Option<String>,
}

impl WithholdingTaxRecord {
    /// Creates a new withholding tax record.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        id: impl Into<String>,
        payment_id: impl Into<String>,
        vendor_id: impl Into<String>,
        withholding_type: WithholdingType,
        statutory_rate: Decimal,
        applied_rate: Decimal,
        base_amount: Decimal,
    ) -> Self {
        let withheld_amount = (base_amount * applied_rate).round_dp(2);
        Self {
            id: id.into(),
            payment_id: payment_id.into(),
            vendor_id: vendor_id.into(),
            withholding_type,
            treaty_rate: None,
            statutory_rate,
            applied_rate,
            base_amount,
            withheld_amount,
            certificate_number: None,
        }
    }

    /// Sets the treaty rate.
    pub fn with_treaty_rate(mut self, rate: Decimal) -> Self {
        self.treaty_rate = Some(rate);
        self
    }

    /// Sets the certificate number.
    pub fn with_certificate_number(mut self, number: impl Into<String>) -> Self {
        self.certificate_number = Some(number.into());
        self
    }

    /// Returns `true` if a tax-treaty benefit has been applied.
    ///
    /// A treaty benefit exists when a treaty rate is present **and** the
    /// applied rate is strictly less than the statutory rate.
    pub fn has_treaty_benefit(&self) -> bool {
        self.treaty_rate.is_some() && self.applied_rate < self.statutory_rate
    }

    /// Computes the savings achieved through the treaty benefit.
    ///
    /// `(statutory_rate - applied_rate) * base_amount`, rounded to 2 dp.
    pub fn treaty_savings(&self) -> Decimal {
        ((self.statutory_rate - self.applied_rate) * self.base_amount).round_dp(2)
    }
}

// ---------------------------------------------------------------------------
// ToNodeProperties implementations
// ---------------------------------------------------------------------------

impl ToNodeProperties for TaxJurisdiction {
    fn node_type_name(&self) -> &'static str {
        "tax_jurisdiction"
    }
    fn node_type_code(&self) -> u16 {
        410
    }
    fn to_node_properties(&self) -> HashMap<String, GraphPropertyValue> {
        let mut p = HashMap::new();
        p.insert("code".into(), GraphPropertyValue::String(self.id.clone()));
        p.insert("name".into(), GraphPropertyValue::String(self.name.clone()));
        p.insert(
            "country".into(),
            GraphPropertyValue::String(self.country_code.clone()),
        );
        if let Some(ref rc) = self.region_code {
            p.insert("region".into(), GraphPropertyValue::String(rc.clone()));
        }
        p.insert(
            "jurisdictionType".into(),
            GraphPropertyValue::String(format!("{:?}", self.jurisdiction_type)),
        );
        p.insert(
            "isActive".into(),
            GraphPropertyValue::Bool(self.vat_registered),
        );
        p
    }
}

impl ToNodeProperties for TaxCode {
    fn node_type_name(&self) -> &'static str {
        "tax_code"
    }
    fn node_type_code(&self) -> u16 {
        411
    }
    fn to_node_properties(&self) -> HashMap<String, GraphPropertyValue> {
        let mut p = HashMap::new();
        p.insert("code".into(), GraphPropertyValue::String(self.code.clone()));
        p.insert(
            "description".into(),
            GraphPropertyValue::String(self.description.clone()),
        );
        p.insert("rate".into(), GraphPropertyValue::Decimal(self.rate));
        p.insert(
            "taxType".into(),
            GraphPropertyValue::String(format!("{:?}", self.tax_type)),
        );
        p.insert(
            "jurisdiction".into(),
            GraphPropertyValue::String(self.jurisdiction_id.clone()),
        );
        p.insert("isActive".into(), GraphPropertyValue::Bool(!self.is_exempt));
        p.insert(
            "isReverseCharge".into(),
            GraphPropertyValue::Bool(self.is_reverse_charge),
        );
        p
    }
}

impl ToNodeProperties for TaxLine {
    fn node_type_name(&self) -> &'static str {
        "tax_line"
    }
    fn node_type_code(&self) -> u16 {
        412
    }
    fn to_node_properties(&self) -> HashMap<String, GraphPropertyValue> {
        let mut p = HashMap::new();
        p.insert(
            "returnId".into(),
            GraphPropertyValue::String(self.document_id.clone()),
        );
        p.insert(
            "lineNumber".into(),
            GraphPropertyValue::Int(self.line_number as i64),
        );
        p.insert(
            "description".into(),
            GraphPropertyValue::String(format!("{:?}", self.document_type)),
        );
        p.insert(
            "amount".into(),
            GraphPropertyValue::Decimal(self.tax_amount),
        );
        p.insert(
            "taxableAmount".into(),
            GraphPropertyValue::Decimal(self.taxable_amount),
        );
        p.insert(
            "taxCode".into(),
            GraphPropertyValue::String(self.tax_code_id.clone()),
        );
        p.insert(
            "jurisdiction".into(),
            GraphPropertyValue::String(self.jurisdiction_id.clone()),
        );
        p.insert(
            "isDeductible".into(),
            GraphPropertyValue::Bool(self.is_deductible),
        );
        p
    }
}

impl ToNodeProperties for TaxReturn {
    fn node_type_name(&self) -> &'static str {
        "tax_return"
    }
    fn node_type_code(&self) -> u16 {
        413
    }
    fn to_node_properties(&self) -> HashMap<String, GraphPropertyValue> {
        let mut p = HashMap::new();
        p.insert(
            "entityCode".into(),
            GraphPropertyValue::String(self.entity_id.clone()),
        );
        p.insert(
            "period".into(),
            GraphPropertyValue::String(format!("{}..{}", self.period_start, self.period_end)),
        );
        p.insert(
            "jurisdiction".into(),
            GraphPropertyValue::String(self.jurisdiction_id.clone()),
        );
        p.insert(
            "filingType".into(),
            GraphPropertyValue::String(format!("{:?}", self.return_type)),
        );
        p.insert(
            "status".into(),
            GraphPropertyValue::String(format!("{:?}", self.status)),
        );
        p.insert(
            "totalTax".into(),
            GraphPropertyValue::Decimal(self.total_output_tax),
        );
        p.insert(
            "taxPaid".into(),
            GraphPropertyValue::Decimal(self.total_input_tax),
        );
        p.insert(
            "balanceDue".into(),
            GraphPropertyValue::Decimal(self.net_payable),
        );
        p.insert(
            "dueDate".into(),
            GraphPropertyValue::Date(self.filing_deadline),
        );
        p.insert("isLate".into(), GraphPropertyValue::Bool(self.is_late));
        p
    }
}

impl ToNodeProperties for TaxProvision {
    fn node_type_name(&self) -> &'static str {
        "tax_provision"
    }
    fn node_type_code(&self) -> u16 {
        414
    }
    fn to_node_properties(&self) -> HashMap<String, GraphPropertyValue> {
        let mut p = HashMap::new();
        p.insert(
            "entityCode".into(),
            GraphPropertyValue::String(self.entity_id.clone()),
        );
        p.insert("period".into(), GraphPropertyValue::Date(self.period));
        p.insert(
            "totalProvision".into(),
            GraphPropertyValue::Decimal(self.current_tax_expense),
        );
        p.insert(
            "deferredAsset".into(),
            GraphPropertyValue::Decimal(self.deferred_tax_asset),
        );
        p.insert(
            "deferredLiability".into(),
            GraphPropertyValue::Decimal(self.deferred_tax_liability),
        );
        p.insert(
            "statutoryRate".into(),
            GraphPropertyValue::Decimal(self.statutory_rate),
        );
        p.insert(
            "effectiveRate".into(),
            GraphPropertyValue::Decimal(self.effective_rate),
        );
        p
    }
}

impl ToNodeProperties for WithholdingTaxRecord {
    fn node_type_name(&self) -> &'static str {
        "withholding_tax_record"
    }
    fn node_type_code(&self) -> u16 {
        415
    }
    fn to_node_properties(&self) -> HashMap<String, GraphPropertyValue> {
        let mut p = HashMap::new();
        p.insert(
            "paymentId".into(),
            GraphPropertyValue::String(self.payment_id.clone()),
        );
        p.insert(
            "vendorId".into(),
            GraphPropertyValue::String(self.vendor_id.clone()),
        );
        p.insert(
            "taxCode".into(),
            GraphPropertyValue::String(format!("{:?}", self.withholding_type)),
        );
        p.insert(
            "grossAmount".into(),
            GraphPropertyValue::Decimal(self.base_amount),
        );
        p.insert(
            "withholdingRate".into(),
            GraphPropertyValue::Decimal(self.applied_rate),
        );
        p.insert(
            "withholdingAmount".into(),
            GraphPropertyValue::Decimal(self.withheld_amount),
        );
        p.insert(
            "treatyApplied".into(),
            GraphPropertyValue::Bool(self.treaty_rate.is_some()),
        );
        if let Some(ref cn) = self.certificate_number {
            p.insert(
                "certificateNumber".into(),
                GraphPropertyValue::String(cn.clone()),
            );
        }
        p
    }
}

impl ToNodeProperties for UncertainTaxPosition {
    fn node_type_name(&self) -> &'static str {
        "uncertain_tax_position"
    }
    fn node_type_code(&self) -> u16 {
        416
    }
    fn to_node_properties(&self) -> HashMap<String, GraphPropertyValue> {
        let mut p = HashMap::new();
        p.insert(
            "entityCode".into(),
            GraphPropertyValue::String(self.entity_id.clone()),
        );
        p.insert(
            "description".into(),
            GraphPropertyValue::String(self.description.clone()),
        );
        p.insert(
            "amount".into(),
            GraphPropertyValue::Decimal(self.tax_benefit),
        );
        p.insert(
            "probability".into(),
            GraphPropertyValue::Decimal(self.recognition_threshold),
        );
        p.insert(
            "reserveAmount".into(),
            GraphPropertyValue::Decimal(self.recognized_amount),
        );
        p.insert(
            "measurementMethod".into(),
            GraphPropertyValue::String(format!("{:?}", self.measurement_method)),
        );
        p
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn test_tax_code_creation() {
        let code = TaxCode::new(
            "TC-001",
            "VAT-STD-20",
            "Standard VAT 20%",
            TaxType::Vat,
            dec!(0.20),
            "JUR-UK",
            NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(),
        )
        .with_expiry_date(NaiveDate::from_ymd_opt(2025, 12, 31).unwrap());

        // tax_amount computation
        assert_eq!(code.tax_amount(dec!(1000.00)), dec!(200.00));
        assert_eq!(code.tax_amount(dec!(0)), dec!(0.00));

        // is_active within range
        assert!(code.is_active(NaiveDate::from_ymd_opt(2024, 6, 15).unwrap()));
        // before effective date
        assert!(!code.is_active(NaiveDate::from_ymd_opt(2023, 12, 31).unwrap()));
        // on expiry date (exclusive)
        assert!(!code.is_active(NaiveDate::from_ymd_opt(2025, 12, 31).unwrap()));
        // well after expiry
        assert!(!code.is_active(NaiveDate::from_ymd_opt(2026, 1, 1).unwrap()));
    }

    #[test]
    fn test_tax_code_exempt() {
        let code = TaxCode::new(
            "TC-002",
            "VAT-EX",
            "VAT Exempt",
            TaxType::Vat,
            dec!(0.20),
            "JUR-UK",
            NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(),
        )
        .with_exempt(true);

        assert_eq!(code.tax_amount(dec!(5000.00)), dec!(0));
    }

    #[test]
    fn test_tax_line_creation() {
        let line = TaxLine::new(
            "TL-001",
            TaxableDocumentType::VendorInvoice,
            "INV-001",
            1,
            "TC-001",
            "JUR-UK",
            dec!(1000.00),
            dec!(200.00),
        );

        assert_eq!(line.effective_rate(), dec!(0.200000));

        // Zero taxable amount should return zero rate
        let zero_line = TaxLine::new(
            "TL-002",
            TaxableDocumentType::VendorInvoice,
            "INV-002",
            1,
            "TC-001",
            "JUR-UK",
            dec!(0),
            dec!(0),
        );
        assert_eq!(zero_line.effective_rate(), dec!(0));
    }

    #[test]
    fn test_tax_return_net_payable() {
        let ret = TaxReturn::new(
            "TR-001",
            "ENT-001",
            "JUR-UK",
            NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(),
            NaiveDate::from_ymd_opt(2024, 3, 31).unwrap(),
            TaxReturnType::VatReturn,
            dec!(50000),
            dec!(30000),
            NaiveDate::from_ymd_opt(2024, 4, 30).unwrap(),
        );

        // Draft is not filed
        assert!(!ret.is_filed());
        assert_eq!(ret.net_payable, dec!(20000));

        // Filed
        let filed = ret.with_filing(NaiveDate::from_ymd_opt(2024, 4, 15).unwrap());
        assert!(filed.is_filed());
        assert!(!filed.is_late);

        // Assessed
        let assessed = TaxReturn::new(
            "TR-002",
            "ENT-001",
            "JUR-UK",
            NaiveDate::from_ymd_opt(2024, 4, 1).unwrap(),
            NaiveDate::from_ymd_opt(2024, 6, 30).unwrap(),
            TaxReturnType::VatReturn,
            dec!(60000),
            dec!(40000),
            NaiveDate::from_ymd_opt(2024, 7, 31).unwrap(),
        )
        .with_status(TaxReturnStatus::Assessed);
        assert!(assessed.is_filed());

        // Paid
        let paid = TaxReturn::new(
            "TR-003",
            "ENT-001",
            "JUR-UK",
            NaiveDate::from_ymd_opt(2024, 7, 1).unwrap(),
            NaiveDate::from_ymd_opt(2024, 9, 30).unwrap(),
            TaxReturnType::IncomeTax,
            dec!(100000),
            dec!(0),
            NaiveDate::from_ymd_opt(2024, 10, 31).unwrap(),
        )
        .with_status(TaxReturnStatus::Paid);
        assert!(paid.is_filed());

        // Amended is not in the "filed" set
        let amended = TaxReturn::new(
            "TR-004",
            "ENT-001",
            "JUR-UK",
            NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(),
            NaiveDate::from_ymd_opt(2024, 3, 31).unwrap(),
            TaxReturnType::VatReturn,
            dec!(50000),
            dec!(30000),
            NaiveDate::from_ymd_opt(2024, 4, 30).unwrap(),
        )
        .with_status(TaxReturnStatus::Amended);
        assert!(!amended.is_filed());
    }

    #[test]
    fn test_tax_provision() {
        let provision = TaxProvision::new(
            "TP-001",
            "ENT-001",
            NaiveDate::from_ymd_opt(2024, 12, 31).unwrap(),
            dec!(250000),
            dec!(80000),
            dec!(120000),
            dec!(0.21),
            dec!(0.245),
        )
        .with_reconciliation_item("State taxes", dec!(0.03))
        .with_reconciliation_item("R&D credits", dec!(-0.015));

        // net deferred tax: 80,000 - 120,000 = -40,000 (net liability)
        assert_eq!(provision.net_deferred_tax(), dec!(-40000));
        assert_eq!(provision.rate_reconciliation.len(), 2);
    }

    #[test]
    fn test_withholding_tax_record() {
        let wht = WithholdingTaxRecord::new(
            "WHT-001",
            "PAY-001",
            "V-100",
            WithholdingType::RoyaltyWithholding,
            dec!(0.30),   // statutory 30%
            dec!(0.10),   // applied 10% (treaty)
            dec!(100000), // base amount
        )
        .with_treaty_rate(dec!(0.10))
        .with_certificate_number("CERT-2024-001");

        assert!(wht.has_treaty_benefit());
        // savings: (0.30 - 0.10) * 100,000 = 20,000
        assert_eq!(wht.treaty_savings(), dec!(20000.00));
        assert_eq!(wht.withheld_amount, dec!(10000.00));
        assert_eq!(wht.certificate_number, Some("CERT-2024-001".to_string()));
    }

    #[test]
    fn test_withholding_no_treaty() {
        let wht = WithholdingTaxRecord::new(
            "WHT-002",
            "PAY-002",
            "V-200",
            WithholdingType::ServiceWithholding,
            dec!(0.25),
            dec!(0.25),
            dec!(50000),
        );

        assert!(!wht.has_treaty_benefit());
        // No savings when applied == statutory
        assert_eq!(wht.treaty_savings(), dec!(0.00));
    }

    #[test]
    fn test_uncertain_tax_position() {
        let utp = UncertainTaxPosition::new(
            "UTP-001",
            "ENT-001",
            "R&D credit claim for software development",
            dec!(500000), // total benefit claimed
            dec!(0.50),   // more-likely-than-not threshold
            dec!(350000), // recognized
            TaxMeasurementMethod::MostLikelyAmount,
        );

        // unrecognized: 500,000 - 350,000 = 150,000
        assert_eq!(utp.unrecognized_amount(), dec!(150000));
    }

    #[test]
    fn test_jurisdiction_hierarchy() {
        let federal = TaxJurisdiction::new(
            "JUR-US",
            "United States - Federal",
            "US",
            JurisdictionType::Federal,
        );
        assert!(!federal.is_subnational());

        let state = TaxJurisdiction::new("JUR-US-CA", "California", "US", JurisdictionType::State)
            .with_region_code("CA")
            .with_parent_jurisdiction_id("JUR-US");
        assert!(state.is_subnational());
        assert_eq!(state.region_code, Some("CA".to_string()));
        assert_eq!(state.parent_jurisdiction_id, Some("JUR-US".to_string()));

        let local = TaxJurisdiction::new(
            "JUR-US-CA-SF",
            "San Francisco",
            "US",
            JurisdictionType::Local,
        )
        .with_parent_jurisdiction_id("JUR-US-CA");
        assert!(local.is_subnational());

        let municipal = TaxJurisdiction::new(
            "JUR-US-NY-NYC",
            "New York City",
            "US",
            JurisdictionType::Municipal,
        )
        .with_parent_jurisdiction_id("JUR-US-NY");
        assert!(municipal.is_subnational());

        let supra = TaxJurisdiction::new(
            "JUR-EU",
            "European Union",
            "EU",
            JurisdictionType::Supranational,
        );
        assert!(!supra.is_subnational());
    }

    #[test]
    fn test_serde_roundtrip() {
        let code = TaxCode::new(
            "TC-SERDE",
            "VAT-STD-20",
            "Standard VAT 20%",
            TaxType::Vat,
            dec!(0.20),
            "JUR-UK",
            NaiveDate::from_ymd_opt(2024, 1, 1).unwrap(),
        )
        .with_expiry_date(NaiveDate::from_ymd_opt(2025, 12, 31).unwrap())
        .with_reverse_charge(true);

        let json = serde_json::to_string_pretty(&code).unwrap();
        let deserialized: TaxCode = serde_json::from_str(&json).unwrap();

        assert_eq!(deserialized.id, code.id);
        assert_eq!(deserialized.code, code.code);
        assert_eq!(deserialized.rate, code.rate);
        assert_eq!(deserialized.tax_type, code.tax_type);
        assert_eq!(deserialized.is_reverse_charge, code.is_reverse_charge);
        assert_eq!(deserialized.effective_date, code.effective_date);
        assert_eq!(deserialized.expiry_date, code.expiry_date);
    }

    #[test]
    fn test_withholding_serde_roundtrip() {
        // With treaty rate (Some)
        let wht = WithholdingTaxRecord::new(
            "WHT-SERDE-1",
            "PAY-001",
            "V-001",
            WithholdingType::RoyaltyWithholding,
            dec!(0.30),
            dec!(0.15),
            dec!(50000),
        )
        .with_treaty_rate(dec!(0.10));

        let json = serde_json::to_string_pretty(&wht).unwrap();
        let deserialized: WithholdingTaxRecord = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.treaty_rate, Some(dec!(0.10)));
        assert_eq!(deserialized.statutory_rate, dec!(0.30));
        assert_eq!(deserialized.applied_rate, dec!(0.15));
        assert_eq!(deserialized.base_amount, dec!(50000));
        assert_eq!(deserialized.withheld_amount, wht.withheld_amount);

        // Without treaty rate (None)
        let wht_no_treaty = WithholdingTaxRecord::new(
            "WHT-SERDE-2",
            "PAY-002",
            "V-002",
            WithholdingType::ServiceWithholding,
            dec!(0.30),
            dec!(0.30),
            dec!(10000),
        );

        let json2 = serde_json::to_string_pretty(&wht_no_treaty).unwrap();
        let deserialized2: WithholdingTaxRecord = serde_json::from_str(&json2).unwrap();
        assert_eq!(deserialized2.treaty_rate, None);
        assert_eq!(deserialized2.statutory_rate, dec!(0.30));
    }
}