1
//! The report text shared by the report natives and the report forms' outcomes.
2

            
3
use chrono::{DateTime, Utc};
4
use finance::error::{FinanceError, ReportError};
5
use server::command::CmdError;
6

            
7
use crate::host_failure::cmd_failure;
8
use server::command::{
9
    ActivityData, ActivityPeriod, BreakdownData, BreakdownPeriod, BreakdownRow, CommodityAmount,
10
    ReportData, ReportNode,
11
};
12

            
13
/// The activity text of `data`, as the natives raise a report failure.
14
483
pub(crate) fn format_activity_text(data: &ActivityData) -> wasmtime::Result<String> {
15
483
    format_activity(data)
16
        .map_err(|err| cmd_failure("report", CmdError::Finance(FinanceError::Report(err))))
17
483
}
18

            
19
483
fn format_activity(data: &ActivityData) -> Result<String, ReportError> {
20
483
    let mut out = String::from("(:activity-report :meta ");
21
483
    out.push_str(&format_meta(
22
483
        data.meta.date_from.as_ref(),
23
483
        data.meta.date_to.as_ref(),
24
483
        data.meta.target_commodity_id.as_ref(),
25
483
    ));
26
483
    out.push_str(" :periods (");
27
483
    for (idx, period) in data.periods.iter().enumerate() {
28
483
        if idx > 0 {
29
            out.push(' ');
30
483
        }
31
483
        format_activity_period_into(&mut out, period)?;
32
    }
33
483
    out.push_str("))");
34
483
    Ok(out)
35
483
}
36

            
37
483
fn format_activity_period_into(
38
483
    out: &mut String,
39
483
    period: &ActivityPeriod,
40
483
) -> Result<(), ReportError> {
41
483
    out.push_str("(:label ");
42
483
    match period.label.as_deref() {
43
160
        Some(label) => out.push_str(&quote_string(label)),
44
323
        None => out.push_str("nil"),
45
    }
46
483
    out.push_str(" :groups (");
47
483
    for (idx, group) in period.groups.iter().enumerate() {
48
966
        let group = group.displayed()?;
49
966
        if idx > 0 {
50
483
            out.push(' ');
51
483
        }
52
966
        out.push_str(&format!(
53
            "(:label {} :flip-sign {} :roots (",
54
966
            quote_string(&group.label),
55
966
            if group.flip_sign { "t" } else { "nil" },
56
        ));
57
966
        for (n, node) in group.roots.iter().enumerate() {
58
484
            if n > 0 {
59
160
                out.push(' ');
60
324
            }
61
484
            format_node_into(out, node);
62
        }
63
966
        out.push_str(") :total (");
64
966
        format_amounts_into(out, &group.total);
65
966
        out.push_str("))");
66
    }
67
483
    out.push_str(") :net (");
68
483
    format_amounts_into(out, &period.displayed_net()?);
69
483
    out.push_str("))");
70
483
    Ok(())
71
483
}
72

            
73
12619
fn format_amounts_into(out: &mut String, amounts: &[CommodityAmount]) {
74
12619
    for (idx, amount) in amounts.iter().enumerate() {
75
14396
        if idx > 0 {
76
5051
            out.push(' ');
77
9345
        }
78
14396
        out.push_str(&format_amount(amount));
79
    }
80
12619
}
81

            
82
14406
fn format_amount(amount: &CommodityAmount) -> String {
83
14406
    format!(
84
        "(:commodity-id \"{}\" :symbol {} :amount {})",
85
14406
        amount.commodity_id,
86
14406
        quote_string(&amount.commodity_symbol),
87
14406
        amount::wire_rational(amount.amount),
88
    )
89
14406
}
90

            
91
323
pub(crate) fn format_breakdown(data: &BreakdownData) -> String {
92
323
    let mut out = String::from("(:category-breakdown :meta ");
93
323
    out.push_str(&format_meta(
94
323
        data.meta.date_from.as_ref(),
95
323
        data.meta.date_to.as_ref(),
96
323
        data.meta.target_commodity_id.as_ref(),
97
323
    ));
98
323
    out.push_str(&format!(
99
323
        " :tag-name {} :periods (",
100
323
        quote_string(&data.tag_name)
101
323
    ));
102
323
    for (idx, period) in data.periods.iter().enumerate() {
103
323
        if idx > 0 {
104
            out.push(' ');
105
323
        }
106
323
        format_breakdown_period_into(&mut out, period);
107
    }
108
323
    out.push_str("))");
109
323
    out
110
323
}
111

            
112
323
fn format_breakdown_period_into(out: &mut String, period: &BreakdownPeriod) {
113
323
    out.push_str("(:label ");
114
323
    match period.label.as_deref() {
115
        Some(label) => out.push_str(&quote_string(label)),
116
323
        None => out.push_str("nil"),
117
    }
118
323
    out.push_str(" :rows (");
119
323
    for (idx, row) in period.rows.iter().enumerate() {
120
10
        if idx > 0 {
121
8
            out.push(' ');
122
2
        }
123
10
        format_breakdown_row_into(out, row);
124
    }
125
323
    out.push_str("))");
126
323
}
127

            
128
10
fn format_breakdown_row_into(out: &mut String, row: &BreakdownRow) {
129
10
    out.push_str(&format!(
130
        "(:tag-value {} :uncategorized {} :amounts (",
131
10
        quote_string(&row.tag_value),
132
10
        if row.is_uncategorized { "t" } else { "nil" },
133
    ));
134
10
    for (idx, amount) in row.amounts.iter().enumerate() {
135
10
        if idx > 0 {
136
            out.push(' ');
137
10
        }
138
10
        out.push_str(&format_amount(amount));
139
    }
140
10
    out.push_str("))");
141
10
}
142

            
143
806
fn format_meta(
144
806
    date_from: Option<&DateTime<Utc>>,
145
806
    date_to: Option<&DateTime<Utc>>,
146
806
    target: Option<&uuid::Uuid>,
147
806
) -> String {
148
806
    format!(
149
        "(:date-from {} :date-to {} :target-commodity-id {})",
150
806
        format_optional_rfc3339(date_from),
151
806
        format_optional_rfc3339(date_to),
152
806
        format_optional_uuid(target),
153
    )
154
806
}
155

            
156
2262
pub(crate) fn format_balance(data: &ReportData) -> String {
157
2262
    let mut out = String::from("(:balance-report :periods (");
158
2262
    for (idx, period) in data.periods.iter().enumerate() {
159
2262
        if idx > 0 {
160
            out.push(' ');
161
2262
        }
162
2262
        out.push_str("(:label ");
163
2262
        match period.label.as_deref() {
164
            Some(label) => out.push_str(&quote_string(label)),
165
2262
            None => out.push_str("nil"),
166
        }
167
2262
        out.push_str(" :roots (");
168
2262
        for (n, node) in period.roots.iter().enumerate() {
169
1323
            if n > 0 {
170
990
                out.push(' ');
171
333
            }
172
1323
            format_node_into(&mut out, node);
173
        }
174
2262
        out.push_str("))");
175
    }
176
2262
    out.push_str("))");
177
2262
    out
178
2262
}
179

            
180
5585
fn format_node_into(out: &mut String, node: &ReportNode) {
181
5585
    out.push_str(&format!(
182
        "(:account-id \"{}\" :account-name {} :account-path {} :depth {} :account-type {} :amounts (",
183
5585
        node.account_id,
184
5585
        quote_string(&node.account_name),
185
5585
        quote_string(&node.account_path),
186
5585
        node.depth,
187
5585
        match node.account_type.as_deref() {
188
3961
            Some(t) => quote_string(t),
189
1624
            None => "nil".to_string(),
190
        },
191
    ));
192
5585
    format_amounts_into(out, &node.amounts);
193
5585
    out.push_str(") :own-amounts (");
194
5585
    format_amounts_into(out, &node.own_amounts);
195
5585
    out.push_str(") :children (");
196
5585
    for (idx, child) in node.children.iter().enumerate() {
197
3778
        if idx > 0 {
198
1147
            out.push(' ');
199
2631
        }
200
3778
        format_node_into(out, child);
201
    }
202
5585
    out.push_str("))");
203
5585
}
204

            
205
1612
fn format_optional_rfc3339(ts: Option<&chrono::DateTime<chrono::Utc>>) -> String {
206
1612
    match ts {
207
1292
        Some(ts) => format!("\"{}\"", ts.to_rfc3339()),
208
320
        None => "nil".to_string(),
209
    }
210
1612
}
211

            
212
806
fn format_optional_uuid(id: Option<&uuid::Uuid>) -> String {
213
806
    match id {
214
        Some(id) => format!("\"{id}\""),
215
806
        None => "nil".to_string(),
216
    }
217
806
}
218

            
219
30996
fn quote_string(s: &str) -> String {
220
30996
    let mut q = String::with_capacity(s.len() + 2);
221
30996
    q.push('"');
222
30996
    for ch in s.chars() {
223
178072
        match ch {
224
            '"' => q.push_str("\\\""),
225
            '\\' => q.push_str("\\\\"),
226
178072
            other => q.push(other),
227
        }
228
    }
229
30996
    q.push('"');
230
30996
    q
231
30996
}