1use serde::{Deserialize, Serialize};
10use uuid::Uuid;
11
12use crate::record::{
13 q_hash_str, EpistemicStatus, EvidenceType, InstantBridge, NQuin, RecordEnvelope,
14 SensitivityClass,
15};
16
17pub const fn div_round_bankers(num: i128, den: i128) -> i64 {
20 if den == 0 {
21 return 0;
22 }
23 let sign = if (num < 0) ^ (den < 0) { -1i128 } else { 1i128 };
24 let n = num.unsigned_abs();
25 let d = den.unsigned_abs();
26 let q = n / d;
27 let r = n % d;
28 let twice_r = r.saturating_mul(2);
29 let rounded = if twice_r > d {
30 q + 1
31 } else if twice_r < d {
32 q
33 } else if q % 2 == 1 {
34 q + 1
35 } else {
36 q
37 };
38 let signed = (rounded as i128) * sign;
39 if signed > i64::MAX as i128 {
40 i64::MAX
41 } else if signed < i64::MIN as i128 {
42 i64::MIN
43 } else {
44 signed as i64
45 }
46}
47
48#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
50#[serde(rename_all = "snake_case")]
51pub enum LedgerBook {
52 #[default]
53 Personal,
54 ProjectPlan,
55 ProjectActual,
56 ProjectFunding,
57 ProjectRoyalty,
58 ProjectTax,
59 FiniteCompensation,
60}
61
62impl LedgerBook {
63 pub const fn as_str(&self) -> &'static str {
65 match self {
66 Self::Personal => "personal",
67 Self::ProjectPlan => "project_plan",
68 Self::ProjectActual => "project_actual",
69 Self::ProjectFunding => "project_funding",
70 Self::ProjectRoyalty => "project_royalty",
71 Self::ProjectTax => "project_tax",
72 Self::FiniteCompensation => "finite_compensation",
73 }
74 }
75}
76
77#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
79pub struct JournalLine {
80 pub account_code: String,
81 pub debit_cents: i64,
82 pub credit_cents: i64,
83 #[serde(default, skip_serializing_if = "Option::is_none")]
84 pub tax_code: Option<String>,
85 #[serde(default, skip_serializing_if = "Option::is_none")]
86 pub dimension_project_id: Option<String>,
87}
88
89impl JournalLine {
90 pub fn debit(account_code: impl Into<String>, debit_cents: i64) -> Self {
92 Self {
93 account_code: account_code.into(),
94 debit_cents,
95 credit_cents: 0,
96 tax_code: None,
97 dimension_project_id: None,
98 }
99 }
100
101 pub fn credit(account_code: impl Into<String>, credit_cents: i64) -> Self {
103 Self {
104 account_code: account_code.into(),
105 debit_cents: 0,
106 credit_cents,
107 tax_code: None,
108 dimension_project_id: None,
109 }
110 }
111
112 pub const fn is_valid(&self) -> bool {
114 self.debit_cents >= 0
115 && self.credit_cents >= 0
116 && !(self.debit_cents > 0 && self.credit_cents > 0)
117 && (self.debit_cents > 0 || self.credit_cents > 0)
118 }
119}
120
121#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
123pub struct JournalEntryRecord {
124 pub id: String,
125 pub book: LedgerBook,
126 pub currency: String,
127 pub memo: String,
128 pub lines: Vec<JournalLine>,
129 pub occurred_at_unix: u32,
130 #[serde(default, skip_serializing_if = "Option::is_none")]
131 pub occurred_at_instant: Option<InstantBridge>,
132 #[serde(default, skip_serializing_if = "Option::is_none")]
133 pub project_id: Option<String>,
134 #[serde(default, skip_serializing_if = "Option::is_none")]
135 pub reversal_of_id: Option<String>,
136}
137
138impl JournalEntryRecord {
139 pub fn new(
141 book: LedgerBook,
142 currency: impl Into<String>,
143 memo: impl Into<String>,
144 lines: Vec<JournalLine>,
145 occurred_at_unix: u32,
146 ) -> Self {
147 Self {
148 id: Uuid::new_v4().to_string(),
149 book,
150 currency: currency.into().to_ascii_uppercase(),
151 memo: memo.into(),
152 lines,
153 occurred_at_unix,
154 occurred_at_instant: Some(InstantBridge::from_coarse(occurred_at_unix)),
155 project_id: None,
156 reversal_of_id: None,
157 }
158 }
159
160 pub fn total_debits(&self) -> i64 {
162 self.lines
163 .iter()
164 .fold(0i64, |acc, line| acc.saturating_add(line.debit_cents))
165 }
166
167 pub fn total_credits(&self) -> i64 {
169 self.lines
170 .iter()
171 .fold(0i64, |acc, line| acc.saturating_add(line.credit_cents))
172 }
173
174 pub fn is_balanced(&self) -> bool {
176 !self.lines.is_empty()
177 && self.lines.iter().all(JournalLine::is_valid)
178 && self.total_debits() > 0
179 && self.total_debits() == self.total_credits()
180 }
181
182 pub fn validate_balance(&self) -> Result<(), String> {
184 if self.lines.is_empty() {
185 return Err("journal entry must contain at least one debit and credit line".to_string());
186 }
187 if !self.lines.iter().all(JournalLine::is_valid) {
188 return Err("journal entry contains invalid negative or dual-sided line".to_string());
189 }
190 let debits = self.total_debits();
191 let credits = self.total_credits();
192 if debits != credits {
193 return Err(format!(
194 "unbalanced journal entry {}: debits ({debits}) != credits ({credits})",
195 self.id
196 ));
197 }
198 Ok(())
199 }
200
201 pub fn compile_to_quins(&self, out: &mut [NQuin]) -> usize {
203 let mut written = 0;
204 let s_id = q_hash_str(&self.id);
205 let ctx = self
206 .project_id
207 .as_deref()
208 .map(q_hash_str)
209 .unwrap_or_else(|| q_hash_str(self.book.as_str()));
210 let meta = SensitivityClass::Restricted.to_metadata_mask() | (self.occurred_at_unix as u64);
211
212 let triples = [
213 (
214 q_hash_str("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"),
215 q_hash_str("https://vocab.Burst.net.au/coop#JournalEntryRecord"),
216 ),
217 (
218 q_hash_str("https://vocab.Burst.net.au/coop#ledgerBook"),
219 q_hash_str(self.book.as_str()),
220 ),
221 (
222 q_hash_str("https://vocab.Burst.net.au/coop#totalDebitsCents"),
223 self.total_debits() as u64,
224 ),
225 (
226 q_hash_str("https://vocab.Burst.net.au/coop#totalCreditsCents"),
227 self.total_credits() as u64,
228 ),
229 ];
230 for (pred, obj) in triples {
231 if written >= out.len() {
232 break;
233 }
234 out[written] = NQuin::new(s_id, pred, obj, ctx, meta);
235 written += 1;
236 }
237 written
238 }
239}
240
241pub fn merge_journal_entries(
244 existing: &[JournalEntryRecord],
245 incoming: &[JournalEntryRecord],
246) -> Vec<JournalEntryRecord> {
247 let mut merged: Vec<JournalEntryRecord> = Vec::with_capacity(existing.len() + incoming.len());
248 for entry in existing.iter().chain(incoming.iter()) {
249 if entry.is_balanced() && !merged.iter().any(|e| e.id == entry.id) {
250 merged.push(entry.clone());
251 }
252 }
253 merged.sort_by(|a, b| {
254 a.occurred_at_unix
255 .cmp(&b.occurred_at_unix)
256 .then_with(|| a.id.cmp(&b.id))
257 });
258 merged
259}
260
261#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
265pub struct LedgerEntry {
266 pub id: String,
267 pub description: String,
268 pub amount_cents: i64,
270 pub currency: String,
272 #[serde(default, skip_serializing_if = "Option::is_none")]
273 pub category: Option<String>,
274 #[serde(default, skip_serializing_if = "Option::is_none")]
275 pub counterparty: Option<String>,
276 #[serde(default, skip_serializing_if = "Option::is_none")]
278 pub project_id: Option<String>,
279 pub occurred_at_unix: u32,
280 #[serde(skip_serializing_if = "Option::is_none", default)]
283 pub occurred_at_instant: Option<InstantBridge>,
284}
285
286impl LedgerEntry {
287 pub fn new(
289 description: impl Into<String>,
290 amount_cents: i64,
291 currency: impl Into<String>,
292 occurred_at_unix: u32,
293 ) -> Self {
294 Self {
295 id: Uuid::new_v4().to_string(),
296 description: description.into(),
297 amount_cents,
298 currency: currency.into().to_ascii_uppercase(),
299 category: None,
300 counterparty: None,
301 project_id: None,
302 occurred_at_unix,
303 occurred_at_instant: Some(InstantBridge::from_coarse(occurred_at_unix)),
304 }
305 }
306
307 pub fn occurred_at(&self) -> InstantBridge {
310 self.occurred_at_instant
311 .unwrap_or_else(|| InstantBridge::from_coarse(self.occurred_at_unix))
312 }
313}
314
315#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
317pub struct CurrencyBalance {
318 pub currency: String,
319 pub net_cents: i64,
320 pub entry_count: usize,
321}
322
323#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
325pub struct BalanceReport {
326 pub by_currency: Vec<CurrencyBalance>,
327 pub total_entries: usize,
328}
329
330pub fn ledger_entry_record_id(uuid: &str) -> String {
332 format!("urn:wellfair:ledger_entry:{uuid}")
333}
334
335pub fn merge_ledger(existing: &[LedgerEntry], incoming: &[LedgerEntry]) -> Vec<LedgerEntry> {
338 let mut merged: Vec<LedgerEntry> = Vec::with_capacity(existing.len() + incoming.len());
339 for entry in existing.iter().chain(incoming.iter()) {
340 if !merged.iter().any(|e| e.id == entry.id) {
341 merged.push(entry.clone());
342 }
343 }
344 merged.sort_by(|a, b| {
345 a.occurred_at_unix
346 .cmp(&b.occurred_at_unix)
347 .then_with(|| a.id.cmp(&b.id))
348 });
349 merged
350}
351
352pub fn derived_balance(entries: &[LedgerEntry]) -> BalanceReport {
355 let unique = merge_ledger(entries, &[]);
356 let mut by_currency: Vec<CurrencyBalance> = Vec::new();
357 for entry in &unique {
358 match by_currency
359 .iter_mut()
360 .find(|c| c.currency == entry.currency)
361 {
362 Some(bal) => {
363 bal.net_cents += entry.amount_cents;
364 bal.entry_count += 1;
365 }
366 None => by_currency.push(CurrencyBalance {
367 currency: entry.currency.clone(),
368 net_cents: entry.amount_cents,
369 entry_count: 1,
370 }),
371 }
372 }
373 by_currency.sort_by(|a, b| a.currency.cmp(&b.currency));
374 BalanceReport {
375 total_entries: unique.len(),
376 by_currency,
377 }
378}
379
380pub fn build_ledger_entry_envelope(
382 entry: &LedgerEntry,
383 owner_did: &str,
384 author_did: &str,
385 asserted_unix: u32,
386 blob_hash: Option<String>,
387) -> RecordEnvelope {
388 RecordEnvelope {
389 id: ledger_entry_record_id(&entry.id),
390 owner_did: owner_did.to_string(),
391 author_did: author_did.to_string(),
392 proxy_did: None,
393 epistemic_status: EpistemicStatus::Asserted,
394 evidence_type: EvidenceType::SelfReported,
395 sensitivity: SensitivityClass::Restricted,
396 asserted_time_unix: asserted_unix,
397 asserted_instant: None,
398 valid_time_start_unix: Some(entry.occurred_at_unix),
399 valid_time_start_instant: entry.occurred_at_instant,
400 valid_time_end_unix: None,
401 valid_time_end_instant: None,
402 predecessor_id: None,
403 blob_hash,
404 tombstone: false,
405 }
406}
407
408pub fn ledger_entry_summary(entry: &LedgerEntry) -> String {
410 serde_json::json!({
411 "id": entry.id,
412 "description": entry.description,
413 "amount_cents": entry.amount_cents,
414 "currency": entry.currency,
415 "category": entry.category,
416 "counterparty": entry.counterparty,
417 "project_id": entry.project_id,
418 "occurred_at_unix": entry.occurred_at_unix,
419 "occurred_at_instant": entry.occurred_at_instant,
420 })
421 .to_string()
422}
423
424pub fn ledger_summary(entry: &LedgerEntry) -> String {
426 ledger_entry_summary(entry)
427}
428
429pub fn parse_ledger_entry_summary(
432 id: impl Into<String>,
433 summary: &str,
434 fallback_occurred_at_unix: u32,
435) -> Option<LedgerEntry> {
436 let v: serde_json::Value = serde_json::from_str(summary).ok()?;
437 let amount_cents = v.get("amount_cents")?.as_i64()?;
438 let currency = v.get("currency")?.as_str()?.to_string();
439 let occurred_at_unix = v
440 .get("occurred_at_unix")
441 .and_then(|x| x.as_u64())
442 .map(|u| u as u32)
443 .unwrap_or(fallback_occurred_at_unix);
444 let occurred_at_instant = v
445 .get("occurred_at_instant")
446 .and_then(|x| serde_json::from_value::<Option<InstantBridge>>(x.clone()).ok())
447 .flatten();
448 let provided_id = id.into();
449 let resolved_id = if provided_id.is_empty() {
450 v.get("id")
451 .and_then(|x| x.as_str())
452 .unwrap_or_default()
453 .to_string()
454 } else {
455 provided_id
456 };
457 Some(LedgerEntry {
458 id: resolved_id,
459 description: v
460 .get("description")
461 .and_then(|x| x.as_str())
462 .unwrap_or_default()
463 .to_string(),
464 amount_cents,
465 currency,
466 category: v
467 .get("category")
468 .and_then(|x| x.as_str())
469 .map(|s| s.to_string()),
470 counterparty: v
471 .get("counterparty")
472 .and_then(|x| x.as_str())
473 .map(|s| s.to_string()),
474 project_id: v
475 .get("project_id")
476 .and_then(|x| x.as_str())
477 .map(|s| s.to_string()),
478 occurred_at_unix,
479 occurred_at_instant,
480 })
481}
482
483pub fn parse_ledger_summary(summary: &str) -> Option<LedgerEntry> {
485 parse_ledger_entry_summary(String::new(), summary, 0)
486}
487
488#[cfg(test)]
489#[path = "finance_tests.rs"]
490mod tests;