1
//! The activity totals on the wire are the ones the server computed.
2

            
3
use nomiscript::{Reader, Value, list_to_vec};
4
use num_rational::Rational64;
5
use rpc::forms::Outcome;
6
use rpc::try_expr_to_value;
7
use scripting::runtime::EvalValue;
8
use server::command::{
9
    ActivityData, ActivityGroupResult, ActivityPeriod, CommodityAmount, ReportMeta, ReportNode,
10
};
11
use uuid::Uuid;
12

            
13
8
fn amount(id: Uuid, symbol: &str, num: i64, den: i64) -> CommodityAmount {
14
8
    CommodityAmount {
15
8
        commodity_id: id,
16
8
        commodity_symbol: symbol.to_string(),
17
8
        amount: Rational64::new(num, den),
18
8
    }
19
8
}
20

            
21
6
fn node(
22
6
    name: &str,
23
6
    depth: usize,
24
6
    amounts: Vec<CommodityAmount>,
25
6
    children: Vec<ReportNode>,
26
6
) -> ReportNode {
27
6
    ReportNode {
28
6
        account_id: Uuid::new_v4(),
29
6
        account_name: name.to_string(),
30
6
        account_path: name.to_string(),
31
6
        depth,
32
6
        account_type: None,
33
6
        own_amounts: amounts.clone(),
34
6
        amounts,
35
6
        children,
36
6
    }
37
6
}
38

            
39
1
fn activity() -> ActivityData {
40
1
    let (usd, eur) = (Uuid::new_v4(), Uuid::new_v4());
41
1
    let salary = node("Salary", 1, vec![amount(usd, "USD", -500, 1)], vec![]);
42
1
    let bonus = node("Bonus", 1, vec![amount(eur, "EUR", -10, 3)], vec![]);
43
1
    let income = ActivityGroupResult::new(
44
1
        "Income".to_string(),
45
1
        true,
46
1
        vec![
47
1
            node(
48
1
                "Income",
49
1
                0,
50
1
                vec![amount(usd, "USD", -500, 1), amount(eur, "EUR", -10, 3)],
51
1
                vec![salary, bonus],
52
1
            ),
53
1
            node("Gifts", 0, vec![amount(usd, "USD", -25, 2)], vec![]),
54
1
        ],
55
1
    )
56
1
    .expect("income total");
57
1
    let rent = node("Rent", 1, vec![amount(usd, "USD", 200, 1)], vec![]);
58
1
    let expense = ActivityGroupResult::new(
59
1
        "Expense".to_string(),
60
1
        false,
61
1
        vec![node(
62
1
            "Expense",
63
1
            0,
64
1
            vec![amount(usd, "USD", 200, 1), amount(eur, "EUR", 1, 3)],
65
1
            vec![rent],
66
1
        )],
67
1
    )
68
1
    .expect("expense total");
69
1
    ActivityData {
70
1
        meta: ReportMeta {
71
1
            date_from: None,
72
1
            date_to: None,
73
1
            target_commodity_id: None,
74
1
        },
75
1
        periods: vec![
76
1
            ActivityPeriod::new(Some("2026-Q1".to_string()), vec![income, expense]).expect("net"),
77
1
        ],
78
1
    }
79
1
}
80

            
81
23
fn field(plist: &Value, key: &str) -> anyhow::Result<Value> {
82
23
    let items = list_to_vec(plist).ok_or_else(|| anyhow::anyhow!("not a plist: {plist:?}"))?;
83
23
    let at = items
84
23
        .iter()
85
106
        .position(|v| matches!(v, Value::Symbol(s) if s.eq_ignore_ascii_case(key)))
86
        .ok_or_else(|| anyhow::anyhow!("missing {key}"))?;
87
23
    items
88
23
        .get(at + 1)
89
23
        .cloned()
90
        .ok_or_else(|| anyhow::anyhow!("no value for {key}"))
91
23
}
92

            
93
7
fn items(list: &Value) -> anyhow::Result<Vec<Value>> {
94
7
    list_to_vec(list).ok_or_else(|| anyhow::anyhow!("not a list: {list:?}"))
95
7
}
96

            
97
8
fn text(value: &Value) -> anyhow::Result<String> {
98
8
    match value {
99
8
        Value::String(s) => Ok(s.clone()),
100
        other => anyhow::bail!("not a string: {other:?}"),
101
    }
102
8
}
103

            
104
4
fn shown(amounts: &Value) -> anyhow::Result<Vec<(String, Rational64)>> {
105
4
    items(amounts)?
106
        .iter()
107
8
        .map(|a| {
108
8
            let symbol = text(&field(a, ":symbol")?)?;
109
8
            let value = match field(a, ":amount")? {
110
                Value::String(s) => s,
111
8
                other => nomiscript::format_value(&other),
112
            };
113
8
            let ratio = match value.split_once('/') {
114
5
                Some((n, d)) => Rational64::new(n.parse()?, d.parse()?),
115
3
                None => Rational64::new(value.parse()?, 1),
116
            };
117
8
            Ok((symbol, ratio))
118
8
        })
119
        .collect()
120
4
}
121

            
122
8
fn pair(symbol: &str, num: i64, den: i64) -> (String, Rational64) {
123
8
    (symbol.to_string(), Rational64::new(num, den))
124
8
}
125

            
126
#[test]
127
1
fn wire_totals_equal_the_server_view() -> anyhow::Result<()> {
128
1
    let EvalValue::String(wire) = Outcome::Activity(activity()).to_value()? else {
129
        anyhow::bail!("activity wire is not a string");
130
    };
131
1
    let program = Reader::parse(&wire)?;
132
1
    let expr = program
133
1
        .exprs
134
1
        .into_iter()
135
1
        .next()
136
        .ok_or_else(|| anyhow::anyhow!("empty wire"))?;
137
1
    let plist = try_expr_to_value(expr)?;
138

            
139
1
    let periods = items(&field(&plist, ":periods")?)?;
140
1
    let period = &periods[0];
141
1
    let groups = items(&field(period, ":groups")?)?;
142
1
    assert_eq!(
143
1
        shown(&field(&groups[0], ":total")?)?,
144
1
        [pair("USD", 1025, 2), pair("EUR", 10, 3)]
145
    );
146
1
    assert_eq!(
147
1
        shown(&field(&groups[1], ":total")?)?,
148
1
        [pair("USD", 200, 1), pair("EUR", 1, 3)]
149
    );
150
1
    assert_eq!(
151
1
        shown(&field(period, ":net")?)?,
152
1
        [pair("USD", 625, 2), pair("EUR", 3, 1)]
153
    );
154
1
    let roots = items(&field(&groups[0], ":roots")?)?;
155
1
    assert_eq!(
156
1
        shown(&field(&roots[0], ":amounts")?)?,
157
1
        [pair("USD", 500, 1), pair("EUR", 10, 3)]
158
    );
159
1
    Ok(())
160
1
}