1
//! Pure, DB-free logical→physical transaction lowering.
2
//!
3
//! This module is the single source of truth for the from→to FX math used by
4
//! every client surface (CLI, TUI, web) and the upcoming B2b RPC native.  No
5
//! database calls, no async.
6

            
7
use chrono::{DateTime, Utc};
8
use num_rational::Rational64;
9
use sqlx::types::Uuid;
10

            
11
use crate::command::CmdError;
12

            
13
mod note;
14
mod raise;
15
mod refusal;
16
mod revision;
17
mod row_tags;
18
pub use note::{is_note, is_note_name, note_value, pick_note};
19
pub use raise::{RaisedRow, raise_transaction};
20
pub use refusal::form_refusal;
21
pub(crate) use revision::hex_digest;
22
pub use revision::{STALE_REVISION, stored_revision};
23
pub use row_tags::{RowTags, ensure_single_line_names, has_line_break, row_tags};
24

            
25
/// One physical ledger entry.
26
#[derive(Debug, Clone)]
27
pub struct PhysicalSplit {
28
    pub account_id: Uuid,
29
    pub commodity_id: Uuid,
30
    pub value: Rational64,
31
    pub id: Uuid,
32
    pub reconcile_state: Option<bool>,
33
}
34

            
35
/// One price-table row linking two physical splits.
36
#[derive(Debug, Clone)]
37
pub struct PriceRow {
38
    pub commodity_id: Uuid,
39
    pub currency_id: Uuid,
40
    pub commodity_split: Uuid,
41
    pub currency_split: Uuid,
42
    pub value_num: i64,
43
    pub value_denom: i64,
44
    pub date: Option<DateTime<Utc>>,
45
}
46

            
47
/// A from→to exchange; `to_amount` is required iff `from_commodity != to_commodity`.
48
#[derive(Debug, Clone)]
49
pub struct LogicalSplit {
50
    pub from: Uuid,
51
    pub to: Uuid,
52
    pub from_commodity: Uuid,
53
    pub to_commodity: Uuid,
54
    pub value: Rational64,
55
    pub to_amount: Option<Rational64>,
56
    /// Reconcile states of the two physical splits; an edit carries them over.
57
    pub from_reconcile: Option<bool>,
58
    pub to_reconcile: Option<bool>,
59
}
60

            
61
52426
fn gcd_i128(mut a: i128, mut b: i128) -> i128 {
62
52426
    a = a.abs();
63
52426
    b = b.abs();
64
161963
    while b != 0 {
65
109537
        let t = a % b;
66
109537
        a = b;
67
109537
        b = t;
68
    }
69
52426
    a
70
52426
}
71

            
72
/// The stored FX rate is the magnitude ratio `value / to_amount` (price ×
73
/// to-side amount = from-side magnitude — the balance-by-construction identity).
74
/// Widen to i128 before cross-multiplying, reduce, normalise sign so the
75
/// denominator is positive, then narrow back to i64.  Overflow returns an error.
76
52426
fn reduced_fx_ratio(value: Rational64, to_amount: Rational64) -> Result<(i64, i64), String> {
77
52426
    if *value.numer() == 0 {
78
        return Err("transaction value must be non-zero for a cross-currency price".to_string());
79
52426
    }
80
52426
    if *to_amount.numer() == 0 {
81
        return Err("to_amount (exchange rate) must be non-zero".to_string());
82
52426
    }
83
52426
    let num = i128::from(*value.numer()) * i128::from(*to_amount.denom());
84
52426
    let den = i128::from(*value.denom()) * i128::from(*to_amount.numer());
85
52426
    let (num, den) = if den < 0 { (-num, -den) } else { (num, den) };
86
52426
    let g = gcd_i128(num, den);
87
52426
    let (num, den) = (num / g, den / g);
88
104850
    let fit = |v: i128, label: &str| {
89
104850
        i64::try_from(v).map_err(|_| format!("price {label} overflows i64 after reduction: {v}"))
90
104850
    };
91
52426
    Ok((fit(num, "value-num")?, fit(den, "value-denom")?))
92
52426
}
93

            
94
/// The input a lowering rule rejected.
95
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
96
pub enum SplitField {
97
    Value,
98
    ToAmount,
99
}
100

            
101
/// A lowering failure; `field` is `None` when the whole row is at fault.
102
#[derive(Debug)]
103
pub struct SplitFault {
104
    pub field: Option<SplitField>,
105
    pub message: String,
106
}
107

            
108
impl SplitFault {
109
1089
    fn at(field: SplitField, message: &str) -> Self {
110
1089
        Self {
111
1089
            field: Some(field),
112
1089
            message: message.to_string(),
113
1089
        }
114
1089
    }
115
}
116

            
117
106822
fn to_side_amount(ls: &LogicalSplit) -> Result<Rational64, SplitFault> {
118
106822
    let zero = Rational64::from_integer(0);
119
106822
    if ls.value <= zero {
120
363
        return Err(SplitFault::at(
121
363
            SplitField::Value,
122
363
            "transaction value must be positive",
123
363
        ));
124
106459
    }
125
106459
    match (ls.from_commodity == ls.to_commodity, ls.to_amount) {
126
362
        (true, Some(_)) => Err(SplitFault::at(
127
362
            SplitField::ToAmount,
128
362
            "to_amount is only valid for cross-currency splits",
129
362
        )),
130
86435
        (true, None) => Ok(ls.value),
131
19300
        (false, Some(amount)) if amount <= zero => Err(SplitFault::at(
132
2
            SplitField::ToAmount,
133
2
            "to_amount must be positive",
134
2
        )),
135
19298
        (false, Some(amount)) => Ok(amount),
136
362
        (false, None) => Err(SplitFault::at(
137
362
            SplitField::ToAmount,
138
362
            "to_amount (required when currencies differ) is required",
139
362
        )),
140
    }
141
106822
}
142

            
143
/// Lower one logical split to two physical splits and an optional price row,
144
/// naming the input a rejection comes from.
145
106822
pub fn lower_logical_split_located(
146
106822
    ls: &LogicalSplit,
147
106822
) -> Result<(PhysicalSplit, PhysicalSplit, Option<PriceRow>), SplitFault> {
148
106822
    let actual_to_amount = to_side_amount(ls)?;
149
105733
    let from_id = Uuid::new_v4();
150
105733
    let to_id = Uuid::new_v4();
151
105733
    let from_phys = PhysicalSplit {
152
105733
        account_id: ls.from,
153
105733
        commodity_id: ls.from_commodity,
154
105733
        value: -ls.value,
155
105733
        id: from_id,
156
105733
        reconcile_state: ls.from_reconcile,
157
105733
    };
158
105733
    let to_phys = PhysicalSplit {
159
105733
        account_id: ls.to,
160
105733
        commodity_id: ls.to_commodity,
161
105733
        value: actual_to_amount,
162
105733
        id: to_id,
163
105733
        reconcile_state: ls.to_reconcile,
164
105733
    };
165
105733
    let price = if ls.from_commodity != ls.to_commodity {
166
        let (value_num, value_denom) =
167
19298
            reduced_fx_ratio(ls.value, actual_to_amount).map_err(|message| SplitFault {
168
2
                field: None,
169
2
                message,
170
2
            })?;
171
19296
        Some(PriceRow {
172
19296
            commodity_id: ls.to_commodity,
173
19296
            currency_id: ls.from_commodity,
174
19296
            commodity_split: to_id,
175
19296
            currency_split: from_id,
176
19296
            value_num,
177
19296
            value_denom,
178
19296
            date: None,
179
19296
        })
180
    } else {
181
86435
        None
182
    };
183
105731
    Ok((from_phys, to_phys, price))
184
106822
}
185

            
186
/// Lower one logical split to two physical splits and an optional price row.
187
15738
pub fn lower_logical_split(
188
15738
    ls: &LogicalSplit,
189
15738
) -> Result<(PhysicalSplit, PhysicalSplit, Option<PriceRow>), CmdError> {
190
15738
    lower_logical_split_located(ls).map_err(|fault| CmdError::Args(fault.message))
191
15738
}
192

            
193
/// Lower a non-empty slice of logical splits into physical splits and price rows.
194
12276
pub fn lower_logical_transaction(
195
12276
    logical_splits: &[LogicalSplit],
196
12276
) -> Result<(Vec<PhysicalSplit>, Vec<PriceRow>), CmdError> {
197
12276
    if logical_splits.is_empty() {
198
1
        return Err(CmdError::Args(
199
1
            "a transaction needs at least one logical split".to_string(),
200
1
        ));
201
12275
    }
202
12275
    let mut splits = Vec::with_capacity(logical_splits.len() * 2);
203
12275
    let mut prices = Vec::new();
204
12275
    for ls in logical_splits {
205
15728
        let (from_phys, to_phys, price) = lower_logical_split(ls)?;
206
15548
        splits.push(from_phys);
207
15548
        splits.push(to_phys);
208
15548
        prices.extend(price);
209
    }
210
12095
    Ok((splits, prices))
211
12276
}
212

            
213
#[cfg(test)]
214
mod raise_tests;
215
#[cfg(test)]
216
mod row_tags_tests;
217
#[cfg(test)]
218
mod tests;