Skip to main content

qualia_core_db/specialized_libs/computational_economics/
accounting.rs

1//! Double-entry accounting kernel.
2//!
3//! Amounts are signed integer minor units (for example cents). Posting debits
4//! and credits must be finite ledger amounts: non-negative, one-sided, and
5//! balanced per journal entry.
6
7#[repr(u8)]
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub enum AccountType {
10    Asset = 0,
11    Liability = 1,
12    Equity = 2,
13    Revenue = 3,
14    Expense = 4,
15}
16
17impl AccountType {
18    /// `true` when `debit_normal`.
19    pub const fn is_debit_normal(self) -> bool {
20        matches!(self, AccountType::Asset | AccountType::Expense)
21    }
22}
23
24#[repr(C)]
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub struct Account {
27    pub id: u64,
28    pub account_type: AccountType,
29}
30
31#[repr(C)]
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub struct Posting {
34    pub entry_id: u64,
35    pub account_id: u64,
36    pub debit: i64,
37    pub credit: i64,
38}
39
40#[repr(C)]
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub struct JournalEntry {
43    pub id: u64,
44    pub posting_start: usize,
45    pub posting_len: usize,
46}
47
48#[repr(C)]
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub struct AccountBalance {
51    pub account_id: u64,
52    pub account_type: AccountType,
53    /// Positive values are favorable to the account's normal balance side.
54    ///
55    /// Assets and expenses compute `debits - credits`; liabilities, equity,
56    /// and revenue compute `credits - debits`.
57    pub balance: i128,
58    pub debit_total: i128,
59    pub credit_total: i128,
60}
61
62#[repr(C)]
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub struct TrialBalance {
65    pub total_debits: i128,
66    pub total_credits: i128,
67    pub debit_balance_total: i128,
68    pub credit_balance_total: i128,
69}
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72pub enum AccountingError {
73    InvalidPosting,
74    EntryNotFound,
75    UnbalancedEntry {
76        entry_id: u64,
77        total_debits: i128,
78        total_credits: i128,
79    },
80    UnknownAccount {
81        account_id: u64,
82    },
83    OutputBufferTooSmall,
84}
85
86/// Zero-heap conservation error for integer minor-unit journal verification.
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88pub enum AccountingConservationError {
89    EmptyJournal,
90    NegativeAmount { index: usize, amount_cents: i64 },
91    UnbalancedJournal { total_debits: i128, total_credits: i128 },
92}
93
94/// Zero-heap integer minor-unit double-entry conservation verifier (`AGENTS.md` ยง0-A).
95///
96/// Verifies that all debit and credit legs are non-negative, non-empty, and satisfy
97/// `sum(debits_cents) == sum(credits_cents) > 0` in `i128` without heap allocation.
98#[inline]
99pub fn verify_integer_journal_conservation(
100    debits_cents: &[i64],
101    credits_cents: &[i64],
102) -> Result<i128, AccountingConservationError> {
103    if debits_cents.is_empty() || credits_cents.is_empty() {
104        return Err(AccountingConservationError::EmptyJournal);
105    }
106    let mut total_debits = 0i128;
107    for (index, &d) in debits_cents.iter().enumerate() {
108        if d < 0 {
109            return Err(AccountingConservationError::NegativeAmount {
110                index,
111                amount_cents: d,
112            });
113        }
114        total_debits += d as i128;
115    }
116    let mut total_credits = 0i128;
117    for (index, &c) in credits_cents.iter().enumerate() {
118        if c < 0 {
119            return Err(AccountingConservationError::NegativeAmount {
120                index,
121                amount_cents: c,
122            });
123        }
124        total_credits += c as i128;
125    }
126    if total_debits == 0 || total_debits != total_credits {
127        return Err(AccountingConservationError::UnbalancedJournal {
128            total_debits,
129            total_credits,
130        });
131    }
132    Ok(total_debits)
133}
134
135/// Zero-heap compilation of a [`Posting`] into a 48-byte [`crate::NQuin`].
136#[inline]
137#[allow(non_snake_case)]
138pub fn compile_journal_Posting_quin(
139    posting: &Posting,
140    journal_context_hash: u64,
141    posted_at_unix: u32,
142) -> Result<crate::NQuin, AccountingError> {
143    validate_posting_amounts(posting)?;
144    let is_debit = posting.debit > 0;
145    let amount = if is_debit {
146        posting.debit as u64
147    } else {
148        posting.credit as u64
149    };
150    let s = posting.entry_id ^ posting.account_id.rotate_left(17);
151    let p = if is_debit {
152        crate::q_hash("https://ns.webizen.org/econ/debitPostingCents")
153    } else {
154        crate::q_hash("https://ns.webizen.org/econ/creditPostingCents")
155    };
156    let o = (0b001u64 << 60) | (amount & 0x0FFF_FFFF_FFFF_FFFF);
157    let metadata = (0b01u64 << 61) | ((posted_at_unix as u64) & 0xFFFF_FFFF);
158    let parity = crate::NQuin::calculate_parity(s, p, o, journal_context_hash, metadata);
159    Ok(crate::NQuin {
160        subject: s,
161        predicate: p,
162        object: o,
163        context: journal_context_hash,
164        metadata,
165        parity,
166    })
167}
168
169/// Snake-case alias for [`compile_journal_Posting_quin`].
170#[inline]
171pub fn compile_journal_posting_quin(
172    posting: &Posting,
173    journal_context_hash: u64,
174    posted_at_unix: u32,
175) -> Result<crate::NQuin, AccountingError> {
176    compile_journal_Posting_quin(posting, journal_context_hash, posted_at_unix)
177}
178
179fn validate_posting_amounts(posting: &Posting) -> Result<(), AccountingError> {
180    if posting.debit < 0 || posting.credit < 0 {
181        return Err(AccountingError::InvalidPosting);
182    }
183    if (posting.debit == 0 && posting.credit == 0) || (posting.debit > 0 && posting.credit > 0) {
184        return Err(AccountingError::InvalidPosting);
185    }
186    Ok(())
187}
188
189fn find_account(accounts: &[Account], account_id: u64) -> Option<Account> {
190    for account in accounts {
191        if account.id == account_id {
192            return Some(*account);
193        }
194    }
195    None
196}
197
198fn validate_known_accounts(
199    accounts: &[Account],
200    postings: &[Posting],
201) -> Result<(), AccountingError> {
202    for posting in postings {
203        validate_posting_amounts(posting)?;
204        if find_account(accounts, posting.account_id).is_none() {
205            return Err(AccountingError::UnknownAccount {
206                account_id: posting.account_id,
207            });
208        }
209    }
210    Ok(())
211}
212
213/// Validate that all postings belonging to `entry_id` form a balanced entry.
214pub fn validate_balanced_entry(entry_id: u64, postings: &[Posting]) -> Result<(), AccountingError> {
215    let mut total_debits = 0i128;
216    let mut total_credits = 0i128;
217    let mut found = false;
218
219    for posting in postings {
220        if posting.entry_id != entry_id {
221            continue;
222        }
223        validate_posting_amounts(posting)?;
224        found = true;
225        total_debits += posting.debit as i128;
226        total_credits += posting.credit as i128;
227    }
228
229    if !found {
230        return Err(AccountingError::EntryNotFound);
231    }
232    if total_debits != total_credits {
233        return Err(AccountingError::UnbalancedEntry {
234            entry_id,
235            total_debits,
236            total_credits,
237        });
238    }
239    Ok(())
240}
241
242/// Validate a journal entry's declared posting slice and balance.
243pub fn validate_journal_entry(
244    entry: &JournalEntry,
245    postings: &[Posting],
246) -> Result<(), AccountingError> {
247    let end = entry
248        .posting_start
249        .checked_add(entry.posting_len)
250        .ok_or(AccountingError::InvalidPosting)?;
251    if entry.posting_len == 0 || end > postings.len() {
252        return Err(AccountingError::InvalidPosting);
253    }
254
255    let slice = &postings[entry.posting_start..end];
256    for posting in slice {
257        if posting.entry_id != entry.id {
258            return Err(AccountingError::InvalidPosting);
259        }
260    }
261    validate_balanced_entry(entry.id, slice)
262}
263
264/// Validate all declared journal entries.
265pub fn validate_journal_entries(
266    entries: &[JournalEntry],
267    postings: &[Posting],
268) -> Result<(), AccountingError> {
269    for entry in entries {
270        validate_journal_entry(entry, postings)?;
271    }
272    Ok(())
273}
274
275/// Compute balances for every supplied account into caller-owned output.
276pub fn account_balances_into(
277    accounts: &[Account],
278    postings: &[Posting],
279    out: &mut [AccountBalance],
280) -> Result<usize, AccountingError> {
281    if out.len() < accounts.len() {
282        return Err(AccountingError::OutputBufferTooSmall);
283    }
284    validate_known_accounts(accounts, postings)?;
285
286    for (idx, account) in accounts.iter().enumerate() {
287        let mut debit_total = 0i128;
288        let mut credit_total = 0i128;
289
290        for posting in postings {
291            if posting.account_id == account.id {
292                debit_total += posting.debit as i128;
293                credit_total += posting.credit as i128;
294            }
295        }
296
297        let balance = if account.account_type.is_debit_normal() {
298            debit_total - credit_total
299        } else {
300            credit_total - debit_total
301        };
302
303        out[idx] = AccountBalance {
304            account_id: account.id,
305            account_type: account.account_type,
306            balance,
307            debit_total,
308            credit_total,
309        };
310    }
311
312    Ok(accounts.len())
313}
314
315/// Aggregate posting totals and account-side trial-balance totals.
316pub fn trial_balance(
317    accounts: &[Account],
318    postings: &[Posting],
319) -> Result<TrialBalance, AccountingError> {
320    validate_known_accounts(accounts, postings)?;
321
322    let mut total_debits = 0i128;
323    let mut total_credits = 0i128;
324    for posting in postings {
325        total_debits += posting.debit as i128;
326        total_credits += posting.credit as i128;
327    }
328    if total_debits != total_credits {
329        return Err(AccountingError::UnbalancedEntry {
330            entry_id: 0,
331            total_debits,
332            total_credits,
333        });
334    }
335
336    let mut debit_balance_total = 0i128;
337    let mut credit_balance_total = 0i128;
338    for account in accounts {
339        let mut debit_total = 0i128;
340        let mut credit_total = 0i128;
341
342        for posting in postings {
343            if posting.account_id == account.id {
344                debit_total += posting.debit as i128;
345                credit_total += posting.credit as i128;
346            }
347        }
348
349        let raw_debit_balance = debit_total - credit_total;
350        if raw_debit_balance >= 0 {
351            debit_balance_total += raw_debit_balance;
352        } else {
353            credit_balance_total += -raw_debit_balance;
354        }
355    }
356
357    Ok(TrialBalance {
358        total_debits,
359        total_credits,
360        debit_balance_total,
361        credit_balance_total,
362    })
363}
364
365#[cfg(test)]
366#[path = "accounting_tests.rs"]
367mod tests;