1use std::borrow::Cow;
9
10use finance::error::ReportError;
11use num_rational::Rational64;
12use sqlx::types::Uuid;
13
14use super::super::{ActivityData, BreakdownData, ReportData, ReportNode, UNCATEGORIZED_KEY};
15
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct AmountView {
18 pub commodity_symbol: String,
19 pub amount: Rational64,
20}
21
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub 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 pub own: Vec<AmountView>,
32}
33
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub 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)]
43pub struct PeriodActivityView {
44 pub label: String,
45 pub groups: Vec<GroupView>,
46 pub net: Vec<AmountView>,
47}
48
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub 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)]
57pub struct BreakdownPeriodView {
58 pub label: String,
59 pub rows: Vec<BreakdownRowView>,
60}
61
62fn amount_views(amounts: &[super::super::CommodityAmount]) -> Vec<AmountView> {
63 amounts
64 .iter()
65 .map(|a| AmountView {
66 commodity_symbol: a.commodity_symbol.clone(),
67 amount: a.amount,
68 })
69 .collect()
70}
71
72fn flatten_nodes(nodes: &[ReportNode], parent: Option<Uuid>, out: &mut Vec<ReportRowView>) {
73 for node in nodes {
74 out.push(ReportRowView {
75 account_id: node.account_id,
76 parent_id: parent,
77 account_name: node.account_name.clone(),
78 depth: node.depth,
79 has_children: !node.children.is_empty(),
80 amounts: amount_views(&node.amounts),
81 own: amount_views(&node.own_amounts),
82 });
83 flatten_nodes(&node.children, Some(node.account_id), out);
84 }
85}
86
87#[must_use]
91pub fn flatten_report_data(data: &ReportData) -> Vec<ReportRowView> {
92 let mut rows = Vec::new();
93 for period in &data.periods {
94 flatten_nodes(&period.roots, None, &mut rows);
95 }
96 rows
97}
98
99pub fn flatten_activity_data(data: &ActivityData) -> Result<Vec<PeriodActivityView>, ReportError> {
107 data.periods
108 .iter()
109 .map(|period| {
110 let groups: Vec<GroupView> = period
111 .groups
112 .iter()
113 .map(|g| {
114 let g = g.displayed()?;
115 let mut rows = Vec::new();
116 flatten_nodes(&g.roots, None, &mut rows);
117 Ok(GroupView {
118 label: g.label,
119 flip_sign: g.flip_sign,
120 rows,
121 total: amount_views(&g.total),
122 })
123 })
124 .collect::<Result<_, ReportError>>()?;
125 Ok(PeriodActivityView {
126 label: period.label.clone().unwrap_or_default(),
127 groups,
128 net: amount_views(&period.displayed_net()?),
129 })
130 })
131 .collect()
132}
133
134#[must_use]
138pub fn flatten_breakdown_data(data: &BreakdownData) -> Vec<BreakdownPeriodView> {
139 data.periods
140 .iter()
141 .map(|p| BreakdownPeriodView {
142 label: p.label.clone().unwrap_or_default(),
143 rows: p
144 .rows
145 .iter()
146 .map(|r| BreakdownRowView {
147 tag_value: r.tag_value.clone(),
148 is_uncategorized: r.is_uncategorized || r.tag_value == UNCATEGORIZED_KEY,
149 amounts: amount_views(&r.amounts),
150 })
151 .collect(),
152 })
153 .collect()
154}
155
156const BOM: &str = "\u{feff}";
158const UNCATEGORIZED: &str = "(uncategorized)";
159
160#[must_use]
162pub fn category_csv(data: &BreakdownData) -> String {
163 breakdown_csv(&data.tag_name, &flatten_breakdown_data(data))
164}
165
166fn breakdown_csv(tag_name: &str, periods: &[BreakdownPeriodView]) -> String {
169 let grouped = periods.iter().any(|period| !period.label.is_empty());
170 let mut out = String::from(BOM);
171 let period_header = grouped.then_some("Period");
172 push_record(
173 &mut out,
174 period_header
175 .into_iter()
176 .chain([tag_name, "Commodity", "Amount"]),
177 );
178 for period in periods {
179 let label = grouped.then_some(period.label.as_str());
180 for row in &period.rows {
181 let category = match row.is_uncategorized {
182 true => UNCATEGORIZED,
183 false => row.tag_value.as_str(),
184 };
185 for amount in &row.amounts {
186 let value = decimal(amount.amount);
187 push_record(
188 &mut out,
189 label.into_iter().chain([
190 category,
191 amount.commodity_symbol.as_str(),
192 value.as_str(),
193 ]),
194 );
195 }
196 }
197 }
198 out
199}
200
201fn push_record<'a>(out: &mut String, fields: impl IntoIterator<Item = &'a str>) {
202 let line = fields.into_iter().map(csv_field).collect::<Vec<_>>();
203 out.push_str(&line.join(","));
204 out.push_str("\r\n");
205}
206
207fn csv_field(field: &str) -> Cow<'_, str> {
209 match field.contains([',', '"', '\n', '\r']) {
210 true => Cow::Owned(format!("\"{}\"", field.replace('"', "\"\""))),
211 false => Cow::Borrowed(field),
212 }
213}
214
215fn decimal(value: Rational64) -> String {
218 let (numer, denom) = (i128::from(*value.numer()), i128::from(*value.denom()));
219 let cents = (numer.abs() * 200 + denom) / (denom * 2);
220 let sign = if numer < 0 && cents > 0 { "-" } else { "" };
221 let (units, fraction) = (cents / 100, cents % 100);
222 match fraction {
223 0 => format!("{sign}{units}"),
224 f if f % 10 == 0 => format!("{sign}{units}.{}", f / 10),
225 f => format!("{sign}{units}.{f:02}"),
226 }
227}
228
229#[cfg(test)]
230#[path = "view_csv_tests.rs"]
231mod csv_tests;
232
233#[cfg(test)]
234mod tests {
235 use super::super::super::{
236 ActivityGroupResult, ActivityPeriod, BreakdownPeriod, BreakdownRow, CommodityAmount,
237 PeriodData, ReportMeta,
238 };
239 use super::*;
240
241 fn commodity(symbol: &str, num: i64) -> CommodityAmount {
242 CommodityAmount {
243 commodity_id: Uuid::from_u128(u128::from(symbol.as_bytes()[0])),
244 commodity_symbol: symbol.to_string(),
245 amount: Rational64::new(num, 1),
246 }
247 }
248
249 fn node(
250 name: &str,
251 depth: usize,
252 amounts: Vec<CommodityAmount>,
253 children: Vec<ReportNode>,
254 ) -> ReportNode {
255 ReportNode {
256 account_id: Uuid::new_v4(),
257 account_name: name.to_string(),
258 account_path: name.to_string(),
259 depth,
260 account_type: None,
261 own_amounts: amounts.clone(),
262 amounts,
263 children,
264 }
265 }
266
267 #[test]
268 fn flatten_report_data_preserves_parent_links() {
269 let child = node("Checking", 1, vec![commodity("USD", 100)], vec![]);
270 let child_id = child.account_id;
271 let parent = node("Assets", 0, vec![commodity("USD", 100)], vec![child]);
272 let parent_id = parent.account_id;
273 let data = ReportData {
274 meta: ReportMeta {
275 date_from: None,
276 date_to: None,
277 target_commodity_id: None,
278 },
279 periods: vec![PeriodData {
280 label: None,
281 roots: vec![parent],
282 }],
283 };
284
285 let rows = flatten_report_data(&data);
286
287 assert_eq!(rows.len(), 2);
288 assert_eq!(rows[0].account_id, parent_id);
289 assert!(rows[0].parent_id.is_none());
290 assert!(rows[0].has_children);
291 assert_eq!(rows[1].account_id, child_id);
292 assert_eq!(rows[1].parent_id, Some(parent_id));
293 assert!(!rows[1].has_children);
294 }
295
296 #[test]
297 fn flatten_activity_data_flips_income_sign_and_nets() {
298 let income = ActivityGroupResult::new(
299 "Income".to_string(),
300 true,
301 vec![node("Salary", 0, vec![commodity("USD", -500)], vec![])],
302 )
303 .expect("income total");
304 let expense = ActivityGroupResult::new(
305 "Expense".to_string(),
306 false,
307 vec![node("Rent", 0, vec![commodity("USD", 200)], vec![])],
308 )
309 .expect("expense total");
310 let data = ActivityData {
311 meta: ReportMeta {
312 date_from: None,
313 date_to: None,
314 target_commodity_id: None,
315 },
316 periods: vec![
317 ActivityPeriod::new(Some("2026-04".to_string()), vec![income, expense])
318 .expect("net"),
319 ],
320 };
321
322 let periods = flatten_activity_data(&data).expect("displayed");
323
324 assert_eq!(periods.len(), 1);
325 let p = &periods[0];
326 assert_eq!(p.label, "2026-04");
327 assert_eq!(
328 p.groups[0].rows[0].amounts[0].amount,
329 Rational64::new(500, 1)
330 );
331 assert_eq!(p.groups[0].total[0].amount, Rational64::new(500, 1));
332 assert_eq!(p.groups[1].total[0].amount, Rational64::new(200, 1));
333 assert_eq!(p.net.len(), 1);
335 assert_eq!(p.net[0].commodity_symbol, "USD");
336 assert_eq!(p.net[0].amount, Rational64::new(300, 1));
337 }
338
339 #[test]
340 fn flatten_breakdown_data_marks_sentinel_uncategorized() {
341 let data = BreakdownData {
342 meta: ReportMeta {
343 date_from: None,
344 date_to: None,
345 target_commodity_id: None,
346 },
347 tag_name: "category".to_string(),
348 periods: vec![BreakdownPeriod {
349 label: None,
350 rows: vec![
351 BreakdownRow {
352 tag_value: "food".to_string(),
353 is_uncategorized: false,
354 amounts: vec![commodity("USD", 50)],
355 },
356 BreakdownRow {
357 tag_value: UNCATEGORIZED_KEY.to_string(),
358 is_uncategorized: true,
359 amounts: vec![commodity("USD", 10)],
360 },
361 ],
362 }],
363 };
364
365 let periods = flatten_breakdown_data(&data);
366
367 assert_eq!(periods[0].rows.len(), 2);
368 assert!(!periods[0].rows[0].is_uncategorized);
369 assert!(periods[0].rows[1].is_uncategorized);
370 }
371}