1
//! View projections shared across report consumers.
2
//!
3
//! Flattens `ReportData` / `ActivityData` / `BreakdownData` server
4
//! responses into small row-oriented structs. Report table handlers, the
5
//! chart adapters in the `plotting` crate, and the CLI all consume these
6
//! instead of re-walking the tree.
7

            
8
use std::borrow::Cow;
9

            
10
use finance::error::ReportError;
11
use num_rational::Rational64;
12
use sqlx::types::Uuid;
13

            
14
use super::super::{ActivityData, BreakdownData, ReportData, ReportNode, UNCATEGORIZED_KEY};
15

            
16
#[derive(Debug, Clone, PartialEq, Eq)]
17
pub struct AmountView {
18
    pub commodity_symbol: String,
19
    pub amount: Rational64,
20
}
21

            
22
#[derive(Debug, Clone, PartialEq, Eq)]
23
pub struct ReportRowView {
24
    pub account_id: Uuid,
25
    pub parent_id: Option<Uuid>,
26
    pub account_name: String,
27
    pub depth: usize,
28
    pub has_children: bool,
29
    pub amounts: Vec<AmountView>,
30
    /// The account's own splits, one entry per commodity (symbols may repeat).
31
    pub own: Vec<AmountView>,
32
}
33

            
34
#[derive(Debug, Clone, PartialEq, Eq)]
35
pub struct GroupView {
36
    pub label: String,
37
    pub flip_sign: bool,
38
    pub rows: Vec<ReportRowView>,
39
    pub total: Vec<AmountView>,
40
}
41

            
42
#[derive(Debug, Clone, PartialEq, Eq)]
43
pub struct PeriodActivityView {
44
    pub label: String,
45
    pub groups: Vec<GroupView>,
46
    pub net: Vec<AmountView>,
47
}
48

            
49
#[derive(Debug, Clone, PartialEq, Eq)]
50
pub struct BreakdownRowView {
51
    pub tag_value: String,
52
    pub is_uncategorized: bool,
53
    pub amounts: Vec<AmountView>,
54
}
55

            
56
#[derive(Debug, Clone, PartialEq, Eq)]
57
pub struct BreakdownPeriodView {
58
    pub label: String,
59
    pub rows: Vec<BreakdownRowView>,
60
}
61

            
62
159853
fn amount_views(amounts: &[super::super::CommodityAmount]) -> Vec<AmountView> {
63
159853
    amounts
64
159853
        .iter()
65
        .map(|a| AmountView {
66
163993
            commodity_symbol: a.commodity_symbol.clone(),
67
163993
            amount: a.amount,
68
163993
        })
69
        .collect()
70
159853
}
71

            
72
79027
fn flatten_nodes(nodes: &[ReportNode], parent: Option<Uuid>, out: &mut Vec<ReportRowView>) {
73
79027
    for node in nodes {
74
60124
        out.push(ReportRowView {
75
60124
            account_id: node.account_id,
76
60124
            parent_id: parent,
77
60124
            account_name: node.account_name.clone(),
78
60124
            depth: node.depth,
79
60124
            has_children: !node.children.is_empty(),
80
60124
            amounts: amount_views(&node.amounts),
81
60124
            own: amount_views(&node.own_amounts),
82
60124
        });
83
60124
        flatten_nodes(&node.children, Some(node.account_id), out);
84
    }
85
79027
}
86

            
87
/// Flatten a point-in-time or period-activity `ReportData` into a single row
88
/// list. The outer `PeriodData` wrapper collapses because Balance always
89
/// returns exactly one period.
90
#[must_use]
91
8641
pub fn flatten_report_data(data: &ReportData) -> Vec<ReportRowView> {
92
8641
    let mut rows = Vec::new();
93
8641
    for period in &data.periods {
94
8461
        flatten_nodes(&period.roots, None, &mut rows);
95
    }
96
8641
    rows
97
8641
}
98

            
99
/// Flatten an `ActivityData` into per-period / per-group row lists with
100
/// totals. `flip_sign` is applied to amounts and to the per-period net,
101
/// following the convention documented in `doc/reporting.org`:
102
/// `Net = sum(group_total * (flip_sign ? +1 : -1))`.
103
///
104
/// # Errors
105
/// [`ReportError::AmountOverflow`] when an amount cannot be negated.
106
5581
pub fn flatten_activity_data(data: &ActivityData) -> Result<Vec<PeriodActivityView>, ReportError> {
107
5581
    data.periods
108
5581
        .iter()
109
5581
        .map(|period| {
110
5581
            let groups: Vec<GroupView> = period
111
5581
                .groups
112
5581
                .iter()
113
10442
                .map(|g| {
114
10442
                    let g = g.displayed()?;
115
10442
                    let mut rows = Vec::new();
116
10442
                    flatten_nodes(&g.roots, None, &mut rows);
117
10442
                    Ok(GroupView {
118
10442
                        label: g.label,
119
10442
                        flip_sign: g.flip_sign,
120
10442
                        rows,
121
10442
                        total: amount_views(&g.total),
122
10442
                    })
123
10442
                })
124
                .collect::<Result<_, ReportError>>()?;
125
            Ok(PeriodActivityView {
126
5581
                label: period.label.clone().unwrap_or_default(),
127
5581
                groups,
128
5581
                net: amount_views(&period.displayed_net()?),
129
            })
130
5581
        })
131
        .collect()
132
5581
}
133

            
134
/// Flatten a `BreakdownData` into per-period row lists. The uncategorized
135
/// sentinel bucket is translated into `is_uncategorized = true` so consumers
136
/// can render it differently without knowing the sentinel value.
137
#[must_use]
138
10621
pub fn flatten_breakdown_data(data: &BreakdownData) -> Vec<BreakdownPeriodView> {
139
10621
    data.periods
140
10621
        .iter()
141
        .map(|p| BreakdownPeriodView {
142
10621
            label: p.label.clone().unwrap_or_default(),
143
10621
            rows: p
144
10621
                .rows
145
10621
                .iter()
146
                .map(|r| BreakdownRowView {
147
23582
                    tag_value: r.tag_value.clone(),
148
23582
                    is_uncategorized: r.is_uncategorized || r.tag_value == UNCATEGORIZED_KEY,
149
23582
                    amounts: amount_views(&r.amounts),
150
23582
                })
151
                .collect(),
152
10621
        })
153
        .collect()
154
10621
}
155

            
156
/// Excel reads a BOM-less CSV in the system code page, mangling non-ASCII names.
157
const BOM: &str = "\u{feff}";
158
const UNCATEGORIZED: &str = "(uncategorized)";
159

            
160
/// The category report as CSV, as the web's export serves it.
161
#[must_use]
162
4680
pub fn category_csv(data: &BreakdownData) -> String {
163
4680
    breakdown_csv(&data.tag_name, &flatten_breakdown_data(data))
164
4680
}
165

            
166
/// One record per category and commodity, in table order; a `Period`
167
/// column leads only when the report is grouped.
168
4682
fn breakdown_csv(tag_name: &str, periods: &[BreakdownPeriodView]) -> String {
169
4682
    let grouped = periods.iter().any(|period| !period.label.is_empty());
170
4682
    let mut out = String::from(BOM);
171
4682
    let period_header = grouped.then_some("Period");
172
4682
    push_record(
173
4682
        &mut out,
174
4682
        period_header
175
4682
            .into_iter()
176
4682
            .chain([tag_name, "Commodity", "Amount"]),
177
4682
    );
178
4682
    for period in periods {
179
4683
        let label = grouped.then_some(period.label.as_str());
180
4683
        for row in &period.rows {
181
8463
            let category = match row.is_uncategorized {
182
1981
                true => UNCATEGORIZED,
183
6482
                false => row.tag_value.as_str(),
184
            };
185
8463
            for amount in &row.amounts {
186
8464
                let value = decimal(amount.amount);
187
8464
                push_record(
188
8464
                    &mut out,
189
8464
                    label.into_iter().chain([
190
8464
                        category,
191
8464
                        amount.commodity_symbol.as_str(),
192
8464
                        value.as_str(),
193
8464
                    ]),
194
8464
                );
195
            }
196
        }
197
    }
198
4682
    out
199
4682
}
200

            
201
13146
fn push_record<'a>(out: &mut String, fields: impl IntoIterator<Item = &'a str>) {
202
13146
    let line = fields.into_iter().map(csv_field).collect::<Vec<_>>();
203
13146
    out.push_str(&line.join(","));
204
13146
    out.push_str("\r\n");
205
13146
}
206

            
207
/// RFC 4180 quoting.
208
39446
fn csv_field(field: &str) -> Cow<'_, str> {
209
39446
    match field.contains([',', '"', '\n', '\r']) {
210
185
        true => Cow::Owned(format!("\"{}\"", field.replace('"', "\"\""))),
211
39261
        false => Cow::Borrowed(field),
212
    }
213
39446
}
214

            
215
/// `value` rounded half away from zero to at most two fraction digits, as the
216
/// table's `formatRational` shows it, without grouping separators.
217
8473
fn decimal(value: Rational64) -> String {
218
8473
    let (numer, denom) = (i128::from(*value.numer()), i128::from(*value.denom()));
219
8473
    let cents = (numer.abs() * 200 + denom) / (denom * 2);
220
8473
    let sign = if numer < 0 && cents > 0 { "-" } else { "" };
221
8473
    let (units, fraction) = (cents / 100, cents % 100);
222
8473
    match fraction {
223
7925
        0 => format!("{sign}{units}"),
224
548
        f if f % 10 == 0 => format!("{sign}{units}.{}", f / 10),
225
6
        f => format!("{sign}{units}.{f:02}"),
226
    }
227
8473
}
228

            
229
#[cfg(test)]
230
#[path = "view_csv_tests.rs"]
231
mod csv_tests;
232

            
233
#[cfg(test)]
234
mod tests {
235
    use super::super::super::{
236
        ActivityGroupResult, ActivityPeriod, BreakdownPeriod, BreakdownRow, CommodityAmount,
237
        PeriodData, ReportMeta,
238
    };
239
    use super::*;
240

            
241
6
    fn commodity(symbol: &str, num: i64) -> CommodityAmount {
242
6
        CommodityAmount {
243
6
            commodity_id: Uuid::from_u128(u128::from(symbol.as_bytes()[0])),
244
6
            commodity_symbol: symbol.to_string(),
245
6
            amount: Rational64::new(num, 1),
246
6
        }
247
6
    }
248

            
249
4
    fn node(
250
4
        name: &str,
251
4
        depth: usize,
252
4
        amounts: Vec<CommodityAmount>,
253
4
        children: Vec<ReportNode>,
254
4
    ) -> ReportNode {
255
4
        ReportNode {
256
4
            account_id: Uuid::new_v4(),
257
4
            account_name: name.to_string(),
258
4
            account_path: name.to_string(),
259
4
            depth,
260
4
            account_type: None,
261
4
            own_amounts: amounts.clone(),
262
4
            amounts,
263
4
            children,
264
4
        }
265
4
    }
266

            
267
    #[test]
268
1
    fn flatten_report_data_preserves_parent_links() {
269
1
        let child = node("Checking", 1, vec![commodity("USD", 100)], vec![]);
270
1
        let child_id = child.account_id;
271
1
        let parent = node("Assets", 0, vec![commodity("USD", 100)], vec![child]);
272
1
        let parent_id = parent.account_id;
273
1
        let data = ReportData {
274
1
            meta: ReportMeta {
275
1
                date_from: None,
276
1
                date_to: None,
277
1
                target_commodity_id: None,
278
1
            },
279
1
            periods: vec![PeriodData {
280
1
                label: None,
281
1
                roots: vec![parent],
282
1
            }],
283
1
        };
284

            
285
1
        let rows = flatten_report_data(&data);
286

            
287
1
        assert_eq!(rows.len(), 2);
288
1
        assert_eq!(rows[0].account_id, parent_id);
289
1
        assert!(rows[0].parent_id.is_none());
290
1
        assert!(rows[0].has_children);
291
1
        assert_eq!(rows[1].account_id, child_id);
292
1
        assert_eq!(rows[1].parent_id, Some(parent_id));
293
1
        assert!(!rows[1].has_children);
294
1
    }
295

            
296
    #[test]
297
1
    fn flatten_activity_data_flips_income_sign_and_nets() {
298
1
        let income = ActivityGroupResult::new(
299
1
            "Income".to_string(),
300
1
            true,
301
1
            vec![node("Salary", 0, vec![commodity("USD", -500)], vec![])],
302
1
        )
303
1
        .expect("income total");
304
1
        let expense = ActivityGroupResult::new(
305
1
            "Expense".to_string(),
306
1
            false,
307
1
            vec![node("Rent", 0, vec![commodity("USD", 200)], vec![])],
308
1
        )
309
1
        .expect("expense total");
310
1
        let data = ActivityData {
311
1
            meta: ReportMeta {
312
1
                date_from: None,
313
1
                date_to: None,
314
1
                target_commodity_id: None,
315
1
            },
316
1
            periods: vec![
317
1
                ActivityPeriod::new(Some("2026-04".to_string()), vec![income, expense])
318
1
                    .expect("net"),
319
1
            ],
320
1
        };
321

            
322
1
        let periods = flatten_activity_data(&data).expect("displayed");
323

            
324
1
        assert_eq!(periods.len(), 1);
325
1
        let p = &periods[0];
326
1
        assert_eq!(p.label, "2026-04");
327
1
        assert_eq!(
328
1
            p.groups[0].rows[0].amounts[0].amount,
329
1
            Rational64::new(500, 1)
330
        );
331
1
        assert_eq!(p.groups[0].total[0].amount, Rational64::new(500, 1));
332
1
        assert_eq!(p.groups[1].total[0].amount, Rational64::new(200, 1));
333
        // Net: income flipped (+500) minus expense (200) = 300.
334
1
        assert_eq!(p.net.len(), 1);
335
1
        assert_eq!(p.net[0].commodity_symbol, "USD");
336
1
        assert_eq!(p.net[0].amount, Rational64::new(300, 1));
337
1
    }
338

            
339
    #[test]
340
1
    fn flatten_breakdown_data_marks_sentinel_uncategorized() {
341
1
        let data = BreakdownData {
342
1
            meta: ReportMeta {
343
1
                date_from: None,
344
1
                date_to: None,
345
1
                target_commodity_id: None,
346
1
            },
347
1
            tag_name: "category".to_string(),
348
1
            periods: vec![BreakdownPeriod {
349
1
                label: None,
350
1
                rows: vec![
351
1
                    BreakdownRow {
352
1
                        tag_value: "food".to_string(),
353
1
                        is_uncategorized: false,
354
1
                        amounts: vec![commodity("USD", 50)],
355
1
                    },
356
1
                    BreakdownRow {
357
1
                        tag_value: UNCATEGORIZED_KEY.to_string(),
358
1
                        is_uncategorized: true,
359
1
                        amounts: vec![commodity("USD", 10)],
360
1
                    },
361
1
                ],
362
1
            }],
363
1
        };
364

            
365
1
        let periods = flatten_breakdown_data(&data);
366

            
367
1
        assert_eq!(periods[0].rows.len(), 2);
368
1
        assert!(!periods[0].rows[0].is_uncategorized);
369
1
        assert!(periods[0].rows[1].is_uncategorized);
370
1
    }
371
}