Skip to main content

qualia_core_db/domains/financial/
tax_schema.rs

1/// Defines modular tax and jurisdictional rulesets to be loaded into the Webizen VM.
2/// These rules are applied to the immutable Quins to compute dynamic, mutable
3/// tax liabilities without polluting the underlying graph.
4
5/// Integer division with banker's rounding (round half to even) (`AGENTS.md` §0-A).
6#[inline]
7pub fn div_round_bankers(numerator: i128, denominator: i128) -> i128 {
8    assert!(denominator > 0, "denominator must be positive");
9    let sign = if numerator < 0 { -1i128 } else { 1i128 };
10    let abs_num = numerator.abs();
11    let q = abs_num / denominator;
12    let r = abs_num % denominator;
13    let twice_r = r * 2;
14    let rounded = if twice_r > denominator || (twice_r == denominator && (q & 1) == 1) {
15        q + 1
16    } else {
17        q
18    };
19    sign * rounded
20}
21
22/// Zero-heap integer minor-unit (`i64`) & basis-point (`u32`) tax withholding calculation
23/// using banker's rounding (`AGENTS.md` §0-A).
24#[inline]
25pub fn compute_withholding_cents_bankers(gross_cents: i64, rate_bps: u32) -> i64 {
26    if gross_cents <= 0 || rate_bps == 0 {
27        return 0;
28    }
29    let capped_bps = rate_bps.min(10_000) as i128;
30    div_round_bankers((gross_cents as i128) * capped_bps, 10_000) as i64
31}
32
33/// Split `gross_cents` into `(net_cents, withheld_tax_cents)` conserving `net + tax == gross`.
34#[inline]
35pub fn split_gross_net_tax_cents_bankers(gross_cents: i64, rate_bps: u32) -> (i64, i64) {
36    let withheld = compute_withholding_cents_bankers(gross_cents, rate_bps);
37    (gross_cents.saturating_sub(withheld), withheld)
38}
39
40pub struct TaxRuleSchema {
41    pub jurisdiction_id: String,
42    pub description: String,
43    pub rules: Vec<TaxRule>,
44}
45
46pub struct TaxRule {
47    pub match_category: String,
48    pub calculation_fn: fn(f64) -> f64,
49}
50
51impl TaxRuleSchema {
52    /// Mock AU GST schema (10% GST on income, 10% credit on expenses)
53    pub fn new_au_gst() -> Self {
54        TaxRuleSchema {
55            jurisdiction_id: "AU_GST_2026".to_string(),
56            description: "Australian Goods and Services Tax (10%)".to_string(),
57            rules: vec![
58                TaxRule {
59                    match_category: "Income".to_string(),
60                    calculation_fn: |amount| amount * 0.10, // 10% GST Owed
61                },
62                TaxRule {
63                    match_category: "Expense".to_string(),
64                    calculation_fn: |amount| amount * -0.10, // 10% GST Credit
65                },
66            ],
67        }
68    }
69
70    /// EU VAT (standard 20%): 20% owed on income, 20% creditable on expenses.
71    pub fn new_eu_vat() -> Self {
72        TaxRuleSchema {
73            jurisdiction_id: "EU_VAT_2026".to_string(),
74            description: "EU Value Added Tax (standard 20%)".to_string(),
75            rules: vec![
76                TaxRule {
77                    match_category: "Income".to_string(),
78                    calculation_fn: |amount| amount * 0.20,
79                },
80                TaxRule {
81                    match_category: "Expense".to_string(),
82                    calculation_fn: |amount| amount * -0.20,
83                },
84            ],
85        }
86    }
87
88    /// US combined sales tax (illustrative ~7% on sales; expenses are not creditable).
89    pub fn new_us_sales_tax() -> Self {
90        TaxRuleSchema {
91            jurisdiction_id: "US_SALES_2026".to_string(),
92            description: "US combined sales tax (~7%)".to_string(),
93            rules: vec![TaxRule {
94                match_category: "Income".to_string(),
95                calculation_fn: |amount| amount * 0.07,
96            }],
97        }
98    }
99
100    /// Zero-rated / exempt jurisdiction — no liability on any category.
101    pub fn new_zero_rated() -> Self {
102        TaxRuleSchema {
103            jurisdiction_id: "ZERO_RATED".to_string(),
104            description: "Zero-rated / exempt".to_string(),
105            rules: Vec::new(),
106        }
107    }
108
109    /// Evaluates a given amount and category against the active ruleset
110    pub fn evaluate(&self, category: &str, amount: f64) -> f64 {
111        for rule in &self.rules {
112            if rule.match_category == category {
113                return (rule.calculation_fn)(amount);
114            }
115        }
116        0.0
117    }
118}
119
120/// A single transaction line to clear — typically projected from a transaction Quin
121/// (`jurisdiction`, `category`, `amount`), so clearing happens "at the nquin level"
122/// without mutating the immutable graph.
123pub struct TaxLineItem<'a> {
124    pub jurisdiction_id: &'a str,
125    pub category: &'a str,
126    pub amount: f64,
127}
128
129/// Net cleared liability for one jurisdiction.
130pub struct JurisdictionLiability {
131    pub jurisdiction_id: String,
132    pub liability: f64,
133}
134
135/// The result of clearing a batch across jurisdictions: per-jurisdiction net
136/// liabilities plus the grand net.
137pub struct ClearingResult {
138    pub per_jurisdiction: Vec<JurisdictionLiability>,
139    pub net_liability: f64,
140}
141
142/// Multi-jurisdiction "Information Banking" tax clearing house.
143pub struct TaxClearingHouse {
144    schemas: Vec<TaxRuleSchema>,
145}
146
147impl TaxClearingHouse {
148    /// Creates a default `TaxClearingHouse`.
149    pub fn new() -> Self {
150        Self {
151            schemas: Vec::new(),
152        }
153    }
154
155    /// Register a jurisdiction schema (builder style).
156    pub fn with_schema(mut self, schema: TaxRuleSchema) -> Self {
157        self.schemas.push(schema);
158        self
159    }
160
161    /// A clearing house pre-loaded with the standard AU-GST / EU-VAT / US-sales /
162    /// zero-rated schemas.
163    pub fn with_standard_schemas() -> Self {
164        Self::new()
165            .with_schema(TaxRuleSchema::new_au_gst())
166            .with_schema(TaxRuleSchema::new_eu_vat())
167            .with_schema(TaxRuleSchema::new_us_sales_tax())
168            .with_schema(TaxRuleSchema::new_zero_rated())
169    }
170
171    fn schema_for(&self, jurisdiction_id: &str) -> Option<&TaxRuleSchema> {
172        self.schemas
173            .iter()
174            .find(|s| s.jurisdiction_id == jurisdiction_id)
175    }
176
177    /// Clear one line item: apply the matching jurisdiction's schema (0 if the
178    /// jurisdiction is unknown — fail-safe, never guesses a foreign rate).
179    pub fn clear_item(&self, jurisdiction_id: &str, category: &str, amount: f64) -> f64 {
180        self.schema_for(jurisdiction_id)
181            .map_or(0.0, |s| s.evaluate(category, amount))
182    }
183
184    /// Clear a batch of line items into per-jurisdiction net liabilities + grand net.
185    pub fn clear_batch(&self, items: &[TaxLineItem]) -> ClearingResult {
186        let mut per: Vec<JurisdictionLiability> = Vec::new();
187        let mut net = 0.0;
188        for item in items {
189            let liability = self.clear_item(item.jurisdiction_id, item.category, item.amount);
190            net += liability;
191            if let Some(j) = per
192                .iter_mut()
193                .find(|j| j.jurisdiction_id == item.jurisdiction_id)
194            {
195                j.liability += liability;
196            } else {
197                per.push(JurisdictionLiability {
198                    jurisdiction_id: item.jurisdiction_id.to_string(),
199                    liability,
200                });
201            }
202        }
203        ClearingResult {
204            per_jurisdiction: per,
205            net_liability: net,
206        }
207    }
208}
209
210impl Default for TaxClearingHouse {
211    fn default() -> Self {
212        Self::new()
213    }
214}
215
216#[cfg(test)]
217mod tests {
218    use super::*;
219
220    #[test]
221    fn per_jurisdiction_rates_apply() {
222        let house = TaxClearingHouse::with_standard_schemas();
223        assert!((house.clear_item("AU_GST_2026", "Income", 1000.0) - 100.0).abs() < 1e-9);
224        assert!((house.clear_item("EU_VAT_2026", "Income", 1000.0) - 200.0).abs() < 1e-9);
225        assert!((house.clear_item("US_SALES_2026", "Income", 1000.0) - 70.0).abs() < 1e-9);
226        assert_eq!(house.clear_item("ZERO_RATED", "Income", 1000.0), 0.0);
227        assert_eq!(house.clear_item("XX_UNKNOWN", "Income", 1000.0), 0.0);
228    }
229
230    #[test]
231    fn batch_clears_net_per_jurisdiction() {
232        let house = TaxClearingHouse::with_standard_schemas();
233        let items = [
234            TaxLineItem {
235                jurisdiction_id: "AU_GST_2026",
236                category: "Income",
237                amount: 1000.0,
238            },
239            TaxLineItem {
240                jurisdiction_id: "AU_GST_2026",
241                category: "Expense",
242                amount: 400.0,
243            },
244            TaxLineItem {
245                jurisdiction_id: "EU_VAT_2026",
246                category: "Income",
247                amount: 500.0,
248            },
249        ];
250        let result = house.clear_batch(&items);
251        assert!((result.net_liability - 160.0).abs() < 1e-9);
252        assert_eq!(result.per_jurisdiction.len(), 2);
253        let au = result
254            .per_jurisdiction
255            .iter()
256            .find(|j| j.jurisdiction_id == "AU_GST_2026")
257            .unwrap();
258        assert!((au.liability - 60.0).abs() < 1e-9);
259        let eu = result
260            .per_jurisdiction
261            .iter()
262            .find(|j| j.jurisdiction_id == "EU_VAT_2026")
263            .unwrap();
264        assert!((eu.liability - 100.0).abs() < 1e-9);
265    }
266
267    #[test]
268    fn withholding_cents_bankers_rounds_half_to_even() {
269        // 50 bps = 0.5%: 100 cents -> 0.5 cents -> rounds to even 0
270        assert_eq!(compute_withholding_cents_bankers(100, 50), 0);
271        // 50 bps = 0.5%: 300 cents -> 1.5 cents -> rounds to even 2
272        assert_eq!(compute_withholding_cents_bankers(300, 50), 2);
273        let (net, tax) = split_gross_net_tax_cents_bankers(10_000, 1_000);
274        assert_eq!(net + tax, 10_000);
275        assert_eq!(tax, 1_000);
276    }
277}