1
//! Wire → view mapping for the three report natives.
2
//!
3
//! All functions are pure and DB-free: they accept a [`nomiscript::Value`]
4
//! decoded from the wire string and project it into the server-side view
5
//! structs the TUI renders.
6

            
7
use std::str::FromStr;
8

            
9
use nomiscript::{Value, list_to_vec};
10
use num_rational::Rational64;
11
use server::command::report::view::{
12
    AmountView, BreakdownPeriodView, BreakdownRowView, GroupView, PeriodActivityView, ReportRowView,
13
};
14
use sqlx::types::Uuid;
15

            
16
use crate::CommandError;
17
use crate::eval::{plist_field, plist_field_raw};
18
use crate::render::reparse_list;
19

            
20
// ---------- rational ----------
21

            
22
4553
fn parse_rational(s: &str) -> Result<Rational64, CommandError> {
23
4553
    if let Some((num, denom)) = s.split_once('/') {
24
567
        let n: i64 = num
25
567
            .parse()
26
            .map_err(|e| CommandError::Command(format!("rational numerator parse '{s}': {e}")))?;
27
567
        let d: i64 = denom
28
567
            .parse()
29
            .map_err(|e| CommandError::Command(format!("rational denominator parse '{s}': {e}")))?;
30
567
        if d == 0 {
31
1
            return Err(CommandError::Command(format!(
32
1
                "rational zero denominator: {s}"
33
1
            )));
34
566
        }
35
566
        Ok(Rational64::new(n, d))
36
    } else {
37
3986
        let n: i64 = s
38
3986
            .parse()
39
            .map_err(|e| CommandError::Command(format!("rational parse '{s}': {e}")))?;
40
3986
        Ok(Rational64::new(n, 1))
41
    }
42
4553
}
43

            
44
// ---------- shared plist helpers ----------
45

            
46
1652
fn reparse(raw: &str, ctx: &str) -> Result<Value, CommandError> {
47
1652
    reparse_list(raw).map_err(|e| CommandError::Command(format!("{ctx}: reparse failed: {e}")))
48
1652
}
49

            
50
1664
fn extract_string(value: &Value, ctx: &str) -> Result<String, CommandError> {
51
1664
    match value {
52
1652
        Value::String(s) => Ok(s.clone()),
53
12
        Value::Nil => Err(CommandError::Command(format!(
54
12
            "{ctx}: got nil, expected string"
55
12
        ))),
56
        other => Err(CommandError::Command(format!(
57
            "{ctx}: unexpected value: {}",
58
            nomiscript::format_value(other)
59
        ))),
60
    }
61
1664
}
62

            
63
14275
fn field_str(plist: &Value, key: &str, ctx: &str) -> Result<String, CommandError> {
64
14275
    plist_field(plist, key).ok_or_else(|| CommandError::Command(format!("{ctx}: missing {key}")))
65
14275
}
66

            
67
833
fn field_usize(plist: &Value, key: &str, ctx: &str) -> Result<usize, CommandError> {
68
833
    let s = field_str(plist, key, ctx)?;
69
833
    usize::from_str(&s).map_err(|e| CommandError::Command(format!("{ctx}: {key} parse error: {e}")))
70
833
}
71

            
72
2678
fn field_bool_sym(plist: &Value, key: &str) -> bool {
73
2678
    plist_field_raw(plist, key).is_some_and(|value| !value.is_nil())
74
2678
}
75

            
76
2416
fn field_list(plist: &Value, key: &str, ctx: &str) -> Result<Vec<Value>, CommandError> {
77
2416
    match plist_field_raw(plist, key) {
78
1166
        Some(Value::Nil) | None => Ok(vec![]),
79
1250
        Some(v) => list_to_vec(&v)
80
            .ok_or_else(|| CommandError::Command(format!("{ctx}: {key} is not a list"))),
81
    }
82
2416
}
83

            
84
// ---------- amounts ----------
85

            
86
4415
fn parse_amounts(amounts_val: &Value, ctx: &str) -> Result<Vec<AmountView>, CommandError> {
87
4415
    let items = match amounts_val {
88
338
        Value::Nil => return Ok(vec![]),
89
4077
        v => list_to_vec(v)
90
            .ok_or_else(|| CommandError::Command(format!("{ctx}: amounts not a list")))?,
91
    };
92
4077
    items
93
4077
        .iter()
94
4549
        .map(|item| {
95
4549
            let symbol = field_str(item, ":symbol", ctx)?;
96
4549
            let amount_s = field_str(item, ":amount", ctx)?;
97
4549
            let amount = parse_rational(&amount_s)?;
98
4549
            Ok(AmountView {
99
4549
                commodity_symbol: symbol,
100
4549
                amount,
101
4549
            })
102
4549
        })
103
        .collect()
104
4415
}
105

            
106
// ---------- ReportNode / balance ----------
107

            
108
833
fn parse_report_node(
109
833
    node: &Value,
110
833
    parent_id: Option<Uuid>,
111
833
    out: &mut Vec<ReportRowView>,
112
833
) -> Result<(), CommandError> {
113
833
    let ctx = "balance-report node";
114
833
    let account_id_s = field_str(node, ":account-id", ctx)?;
115
833
    let account_id = Uuid::parse_str(&account_id_s)
116
        .map_err(|e| CommandError::Command(format!("{ctx}: account-id parse: {e}")))?;
117
833
    let account_name = field_str(node, ":account-name", ctx)?;
118
833
    let depth = field_usize(node, ":depth", ctx)?;
119

            
120
833
    let amounts = required_amounts(node, ":amounts", ctx)?;
121
832
    let own = required_amounts(node, ":own-amounts", ctx)?;
122

            
123
819
    let children_val = plist_field_raw(node, ":children").unwrap_or(Value::Nil);
124
819
    let children = match &children_val {
125
603
        Value::Nil => vec![],
126
216
        v => list_to_vec(v)
127
            .ok_or_else(|| CommandError::Command(format!("{ctx}: :children not a list")))?,
128
    };
129

            
130
819
    out.push(ReportRowView {
131
819
        account_id,
132
819
        parent_id,
133
819
        account_name,
134
819
        depth,
135
819
        has_children: !children.is_empty(),
136
819
        amounts,
137
819
        own,
138
819
    });
139

            
140
819
    for child in &children {
141
312
        parse_report_node(child, Some(account_id), out)?;
142
    }
143
819
    Ok(())
144
833
}
145

            
146
/// Map the `balance-report` wire string into a flat row list for the chart adapter.
147
1229
pub fn value_to_balance_rows(value: &Value) -> Result<Vec<ReportRowView>, CommandError> {
148
1229
    let raw = extract_string(value, "balance-report")?;
149
1217
    let plist = reparse(&raw, "balance-report")?;
150
1217
    let periods = field_list(&plist, ":periods", "balance-report")?;
151
1217
    let mut rows = Vec::new();
152
1217
    for period in &periods {
153
400
        let roots = field_list(period, ":roots", "balance-report period")?;
154
400
        for root in &roots {
155
412
            parse_report_node(root, None, &mut rows)?;
156
        }
157
    }
158
1203
    Ok(rows)
159
1229
}
160

            
161
// ---------- activity ----------
162

            
163
/// An amount list that the server must send; absent is a malformed report.
164
1872
fn required_amounts(node: &Value, key: &str, ctx: &str) -> Result<Vec<AmountView>, CommandError> {
165
1872
    let raw = plist_field_raw(node, key)
166
14
        .ok_or_else(|| CommandError::Command(format!("{ctx}: missing {key}")))?;
167
1858
    parse_amounts(&raw, ctx)
168
1872
}
169

            
170
/// A period's `:label`; `nil`, the label of an ungrouped report, is no label.
171
243
fn period_label(period: &Value) -> String {
172
243
    match plist_field_raw(period, ":label") {
173
73
        Some(Value::String(label)) => label,
174
170
        _ => String::new(),
175
    }
176
243
}
177

            
178
/// Map the `activity-report` wire string into period views for the chart adapter.
179
146
pub fn value_to_activity_periods(value: &Value) -> Result<Vec<PeriodActivityView>, CommandError> {
180
146
    let raw = extract_string(value, "activity-report")?;
181
146
    let plist = reparse(&raw, "activity-report")?;
182
146
    let period_vals = field_list(&plist, ":periods", "activity-report")?;
183

            
184
146
    period_vals
185
146
        .iter()
186
86
        .map(|period| {
187
86
            let label = period_label(period);
188
86
            let group_vals = field_list(period, ":groups", "activity period")?;
189

            
190
86
            let groups: Vec<GroupView> = group_vals
191
86
                .iter()
192
121
                .map(|g| {
193
121
                    let g_label = field_str(g, ":label", "activity group")?;
194
121
                    let flip_sign = field_bool_sym(g, ":flip-sign");
195
121
                    let root_vals = field_list(g, ":roots", "activity group")?;
196
121
                    let mut rows = Vec::new();
197
121
                    for root in &root_vals {
198
109
                        parse_report_node(root, None, &mut rows)?;
199
                    }
200
121
                    let total = required_amounts(g, ":total", "activity group")?;
201
121
                    Ok(GroupView {
202
121
                        label: g_label,
203
121
                        flip_sign,
204
121
                        rows,
205
121
                        total,
206
121
                    })
207
121
                })
208
                .collect::<Result<_, CommandError>>()?;
209

            
210
86
            let net = required_amounts(period, ":net", "activity period")?;
211
86
            Ok(PeriodActivityView { label, groups, net })
212
86
        })
213
        .collect()
214
146
}
215

            
216
// ---------- breakdown ----------
217

            
218
/// Map the `category-breakdown` wire string into period views for the chart adapter.
219
289
pub fn value_to_breakdown_periods(value: &Value) -> Result<Vec<BreakdownPeriodView>, CommandError> {
220
289
    let raw = extract_string(value, "category-breakdown")?;
221
289
    let plist = reparse(&raw, "category-breakdown")?;
222
289
    let period_vals = field_list(&plist, ":periods", "category-breakdown")?;
223

            
224
289
    period_vals
225
289
        .iter()
226
157
        .map(|period| {
227
157
            let label = period_label(period);
228
157
            let row_vals = field_list(period, ":rows", "breakdown period")?;
229

            
230
157
            let rows: Vec<BreakdownRowView> = row_vals
231
157
                .iter()
232
2557
                .map(|row| {
233
2557
                    let tag_value = field_str(row, ":tag-value", "breakdown row")?;
234
2557
                    let is_uncategorized = field_bool_sym(row, ":uncategorized");
235
2557
                    let amounts_val = plist_field_raw(row, ":amounts").unwrap_or(Value::Nil);
236
2557
                    let amounts = parse_amounts(&amounts_val, "breakdown row")?;
237
2557
                    Ok(BreakdownRowView {
238
2557
                        tag_value,
239
2557
                        is_uncategorized,
240
2557
                        amounts,
241
2557
                    })
242
2557
                })
243
                .collect::<Result<_, CommandError>>()?;
244

            
245
157
            Ok(BreakdownPeriodView { label, rows })
246
157
        })
247
        .collect()
248
289
}
249

            
250
#[cfg(test)]
251
mod tests {
252
    use super::*;
253

            
254
8
    fn parse(s: &str) -> Value {
255
8
        Value::String(s.to_string())
256
8
    }
257

            
258
    #[test]
259
1
    fn balance_rows_keep_own_amounts_apart_from_the_roll_up() {
260
        let one =
261
1
            r#"(:commodity-id "00000000-0000-0000-0000-000000000001" :symbol "$" :amount 10)"#;
262
1
        let two = r#"(:commodity-id "00000000-0000-0000-0000-000000000002" :symbol "$" :amount 5)"#;
263
1
        let wire = format!(
264
1
            r#"(:balance-report :periods ((:label nil :roots ((:account-id "00000000-0000-0000-0000-00000000000a" :account-name "A" :account-path "A" :depth 0 :account-type nil :amounts ({one} {two}) :own-amounts ({one} {two}) :children ())))))"#
265
        );
266
1
        let rows = value_to_balance_rows(&parse(&wire)).unwrap();
267
1
        assert_eq!(rows[0].own, rows[0].amounts);
268
1
        assert_eq!(rows[0].own.len(), 2);
269
1
        assert_eq!(rows[0].own[1].amount, Rational64::new(5, 1));
270
1
    }
271

            
272
    #[test]
273
1
    fn a_balance_node_without_amounts_or_own_amounts_is_an_error() {
274
2
        let node = |keys: &str| {
275
2
            format!(
276
2
                r#"(:balance-report :periods ((:label nil :roots ((:account-id "00000000-0000-0000-0000-00000000000a" :account-name "A" :account-path "A" :depth 0 :account-type nil {keys} :children ())))))"#
277
            )
278
2
        };
279
1
        let no_own = value_to_balance_rows(&parse(&node(":amounts ()"))).unwrap_err();
280
1
        assert!(no_own.to_string().contains(":own-amounts"), "{no_own}");
281
1
        let no_amounts = value_to_balance_rows(&parse(&node(":own-amounts ()"))).unwrap_err();
282
1
        assert!(no_amounts.to_string().contains(":amounts"), "{no_amounts}");
283
1
    }
284

            
285
    #[test]
286
1
    fn parse_rational_integer() {
287
1
        assert_eq!(parse_rational("42").unwrap(), Rational64::new(42, 1));
288
1
    }
289

            
290
    #[test]
291
1
    fn parse_rational_fraction() {
292
1
        assert_eq!(parse_rational("3/4").unwrap(), Rational64::new(3, 4));
293
1
    }
294

            
295
    #[test]
296
1
    fn parse_rational_negative() {
297
1
        assert_eq!(parse_rational("-5/2").unwrap(), Rational64::new(-5, 2));
298
1
    }
299

            
300
    #[test]
301
1
    fn parse_rational_zero_denom_is_error() {
302
1
        assert!(parse_rational("1/0").is_err());
303
1
    }
304

            
305
    #[test]
306
1
    fn value_to_balance_rows_single_node_two_amounts() {
307
1
        let wire = r#"(:balance-report :periods ((:label nil :roots ((:account-id "00000000-0000-0000-0000-000000000000" :account-name "Assets" :account-path "Assets" :depth 0 :account-type "asset" :amounts ((:commodity-id "00000000-0000-0000-0000-000000000000" :symbol "USD" :amount 100) (:commodity-id "00000000-0000-0000-0000-000000000000" :symbol "EUR" :amount 50)) :own-amounts ((:commodity-id "00000000-0000-0000-0000-000000000000" :symbol "USD" :amount 100) (:commodity-id "00000000-0000-0000-0000-000000000000" :symbol "EUR" :amount 50)) :children ())))))"#;
308
1
        let rows = value_to_balance_rows(&parse(wire)).expect("parse ok");
309
1
        assert_eq!(rows.len(), 1);
310
1
        assert_eq!(rows[0].account_name, "Assets");
311
1
        assert_eq!(rows[0].amounts.len(), 2, "both commodities must be present");
312
1
        assert!(rows[0].amounts.iter().any(|a| a.commodity_symbol == "USD"));
313
2
        assert!(rows[0].amounts.iter().any(|a| a.commodity_symbol == "EUR"));
314
1
    }
315

            
316
    #[test]
317
1
    fn value_to_balance_rows_empty_periods() {
318
1
        let wire = "(:balance-report :periods ())";
319
1
        let rows = value_to_balance_rows(&parse(wire)).expect("empty ok");
320
1
        assert!(rows.is_empty());
321
1
    }
322

            
323
    #[test]
324
1
    fn value_to_activity_periods_parses_groups() {
325
1
        let wire = r#"(:activity-report :meta nil :periods ((:label "2026-Q1" :groups ((:label "Income" :flip-sign t :roots ((:account-id "00000000-0000-0000-0000-000000000000" :account-name "Salary" :account-path "Income:Salary" :depth 0 :account-type nil :amounts ((:commodity-id "00000000-0000-0000-0000-000000000000" :symbol "USD" :amount 1000)) :own-amounts ((:commodity-id "00000000-0000-0000-0000-000000000000" :symbol "USD" :amount 1000)) :children ())) :total ((:commodity-id "00000000-0000-0000-0000-000000000000" :symbol "USD" :amount 1000)))) :net ((:commodity-id "00000000-0000-0000-0000-000000000000" :symbol "USD" :amount -1000)))))"#;
326
1
        let periods = value_to_activity_periods(&parse(wire)).expect("parse ok");
327
1
        assert_eq!(periods.len(), 1);
328
1
        assert_eq!(periods[0].label, "2026-Q1");
329
1
        assert_eq!(
330
1
            periods[0].groups[0].total[0].amount,
331
1
            Rational64::new(1000, 1)
332
        );
333
1
        assert_eq!(periods[0].net[0].amount, Rational64::new(-1000, 1));
334
1
        assert_eq!(periods[0].groups.len(), 1);
335
1
        assert_eq!(periods[0].groups[0].label, "Income");
336
1
        assert_eq!(
337
1
            periods[0].groups[0].rows[0].amounts[0].amount,
338
1
            Rational64::new(1000, 1)
339
        );
340
1
    }
341

            
342
    #[test]
343
1
    fn value_to_breakdown_periods_parses_rows() {
344
1
        let wire = r#"(:category-breakdown :meta nil :tag-name "category" :periods ((:label nil :rows ((:tag-value "Food" :uncategorized nil :amounts ((:commodity-id "00000000-0000-0000-0000-000000000000" :symbol "USD" :amount 200)))))))"#;
345
1
        let periods = value_to_breakdown_periods(&parse(wire)).expect("parse ok");
346
1
        assert_eq!(periods.len(), 1);
347
1
        assert_eq!(periods[0].rows.len(), 1);
348
1
        assert_eq!(periods[0].rows[0].tag_value, "Food");
349
1
        assert_eq!(
350
1
            periods[0].rows[0].amounts[0].amount,
351
1
            Rational64::new(200, 1)
352
        );
353
1
        assert_eq!(periods[0].label, "");
354
1
    }
355

            
356
    #[test]
357
1
    fn an_ungrouped_activity_period_has_no_label() {
358
1
        let wire = r#"(:activity-report :meta nil :periods ((:label nil :groups () :net ())))"#;
359
1
        let periods = value_to_activity_periods(&parse(wire)).expect("parse ok");
360
1
        assert_eq!(periods[0].label, "");
361
1
    }
362
}