1
//! Report-domain natives. Wraps `server::command::{ActivityReport,
2
//! CategoryBreakdown}`.
3

            
4
use chrono::{DateTime, Utc};
5
use forms::{FormValues, REPORT_BALANCE, REPORT_CATEGORY};
6
use scripting::runtime::{alloc_string_ref, read_string_arg};
7
use server::command::CmdResult;
8
use server::command::report::view::category_csv;
9
use server::command::report::{ActivityReport, CategoryBreakdown};
10
use wasmtime::{ArrayRef, Linker, Rooted};
11

            
12
use crate::forms::{
13
    ReportOutcome, format_activity_text, format_balance, format_breakdown, typed_report_on,
14
    unexpected,
15
};
16
use crate::host_failure::cmd_failure;
17
use crate::natives::args::{args_error, required};
18
use crate::natives::forms::{native_failure, report_outcome};
19
use crate::natives::native::register_native;
20
use crate::session::SessionData;
21

            
22
pub const REGISTERED_COMMANDS: &[&str] = &[
23
    "balance-report",
24
    "activity-report",
25
    "category-breakdown",
26
    "report-csv",
27
];
28

            
29
230200
pub fn register(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
30
230200
    register_readonly(linker)?;
31
230200
    register_native(
32
230200
        linker,
33
230200
        "report_report_csv",
34
640
        |caller, (payload_arg,): (Option<Rooted<ArrayRef>>,)| {
35
640
            Box::pin(async move {
36
640
                let user_id = caller.data().ctx().user_id;
37
640
                let payload = read_string_arg(caller, payload_arg)?
38
                    .ok_or_else(|| args_error("report-csv: missing :values"))?;
39
640
                let csv = run_report_csv(user_id, &payload).await?;
40
480
                Ok(Some(alloc_string_ref(caller, csv.as_bytes())?))
41
640
            })
42
640
        },
43
    )
44
230200
}
45

            
46
/// The report natives on the render allowlist.
47
236811
pub fn register_readonly(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
48
236811
    register_native(linker, "report_balance_report", |caller, ()| {
49
1440
        Box::pin(async move {
50
1440
            let user_id = caller.data().ctx().user_id;
51
1440
            let payload = run_balance_report(user_id, Utc::now()).await?;
52
1440
            Ok(Some(alloc_string_ref(caller, payload.as_bytes())?))
53
1440
        })
54
1440
    })?;
55
236811
    register_native(
56
236811
        linker,
57
236811
        "report_activity_report",
58
160
        |caller, (from_arg, to_arg): (Option<Rooted<ArrayRef>>, Option<Rooted<ArrayRef>>)| {
59
160
            Box::pin(async move {
60
160
                let user_id = caller.data().ctx().user_id;
61
160
                let from = read_string_arg(caller, from_arg)?;
62
160
                let to = read_string_arg(caller, to_arg)?;
63
160
                let payload = run_activity_report(user_id, from, to).await?;
64
160
                Ok(Some(alloc_string_ref(caller, payload.as_bytes())?))
65
160
            })
66
160
        },
67
    )?;
68
236811
    register_native(
69
236811
        linker,
70
236811
        "report_category_breakdown",
71
160
        |caller, (from_arg, to_arg): (Option<Rooted<ArrayRef>>, Option<Rooted<ArrayRef>>)| {
72
160
            Box::pin(async move {
73
160
                let user_id = caller.data().ctx().user_id;
74
160
                let from = read_string_arg(caller, from_arg)?;
75
160
                let to = read_string_arg(caller, to_arg)?;
76
160
                let payload = run_category_breakdown(user_id, from, to).await?;
77
160
                Ok(Some(alloc_string_ref(caller, payload.as_bytes())?))
78
160
            })
79
160
        },
80
    )?;
81
236811
    Ok(())
82
236811
}
83

            
84
/// The category report of `payload`, as `submit-form "report-category"` runs it, as CSV.
85
///
86
/// # Errors
87
/// An unreadable payload or invalid values (`form-invalid`), or a failed report.
88
2403
pub async fn run_report_csv(user_id: uuid::Uuid, payload: &str) -> wasmtime::Result<String> {
89
2403
    match report_outcome(user_id, "report-category", payload).await? {
90
2082
        ReportOutcome::Breakdown(data) => Ok(category_csv(&data)),
91
        _ => Err(native_failure(unexpected(&REPORT_CATEGORY))),
92
    }
93
2403
}
94

            
95
326
fn parse_date_args(
96
326
    name: &str,
97
326
    from_arg: Option<String>,
98
326
    to_arg: Option<String>,
99
326
) -> wasmtime::Result<(DateTime<Utc>, DateTime<Utc>)> {
100
326
    let from_raw = required(name, "date-from", from_arg)?;
101
324
    let to_raw = required(name, "date-to", to_arg)?;
102
324
    let from = DateTime::parse_from_rfc3339(&from_raw)
103
322
        .map(|d| d.with_timezone(&Utc))
104
2
        .map_err(|err| args_error(format!("{name}: invalid :date-from '{from_raw}': {err}")))?;
105
322
    let to = DateTime::parse_from_rfc3339(&to_raw)
106
322
        .map(|d| d.with_timezone(&Utc))
107
        .map_err(|err| args_error(format!("{name}: invalid :date-to '{to_raw}': {err}")))?;
108
322
    Ok((from, to))
109
326
}
110

            
111
163
pub(crate) async fn run_activity_report(
112
163
    user_id: uuid::Uuid,
113
163
    from_arg: Option<String>,
114
163
    to_arg: Option<String>,
115
163
) -> wasmtime::Result<String> {
116
163
    let (from, to) = parse_date_args("activity-report", from_arg, to_arg)?;
117
161
    match ActivityReport::new()
118
161
        .user_id(user_id)
119
161
        .date_from(from)
120
161
        .date_to(to)
121
161
        .run()
122
161
        .await
123
    {
124
161
        Ok(Some(CmdResult::Activity(data))) => format_activity_text(&data),
125
        Ok(Some(other)) => Err(wasmtime::Error::msg(format!(
126
            "activity-report: expected Activity, got {other:?}"
127
        ))),
128
        Ok(None) => Ok("(:activity-report :periods ())".to_string()),
129
        Err(err) => Err(cmd_failure("activity-report", err)),
130
    }
131
163
}
132

            
133
163
pub(crate) async fn run_category_breakdown(
134
163
    user_id: uuid::Uuid,
135
163
    from_arg: Option<String>,
136
163
    to_arg: Option<String>,
137
163
) -> wasmtime::Result<String> {
138
163
    let (from, to) = parse_date_args("category-breakdown", from_arg, to_arg)?;
139
161
    match CategoryBreakdown::new()
140
161
        .user_id(user_id)
141
161
        .date_from(from)
142
161
        .date_to(to)
143
161
        .run()
144
161
        .await
145
    {
146
161
        Ok(Some(CmdResult::Breakdown(data))) => Ok(format_breakdown(&data)),
147
        Ok(Some(other)) => Err(wasmtime::Error::msg(format!(
148
            "category-breakdown: expected Breakdown, got {other:?}"
149
        ))),
150
        Ok(None) => Ok("(:category-breakdown :periods ())".to_string()),
151
        Err(err) => Err(cmd_failure("category-breakdown", err)),
152
    }
153
163
}
154

            
155
/// The balance report of `user_id` with the form's default as-of, the end of the local day of `now`.
156
1443
pub(crate) async fn run_balance_report(
157
1443
    user_id: uuid::Uuid,
158
1443
    now: DateTime<Utc>,
159
1443
) -> wasmtime::Result<String> {
160
1443
    let outcome = typed_report_on(user_id, &REPORT_BALANCE, &FormValues::default(), now)
161
1443
        .await
162
1443
        .map_err(native_failure)?;
163
1442
    match outcome {
164
1442
        ReportOutcome::Balance(data) => Ok(format_balance(&data)),
165
        _ => Err(native_failure(unexpected(&REPORT_BALANCE))),
166
    }
167
1443
}
168

            
169
#[cfg(test)]
170
mod tests {
171
    use super::*;
172
    use num_rational::Rational64;
173
    use server::command::{CommodityAmount, PeriodData, ReportData, ReportMeta, ReportNode};
174
    use uuid::Uuid;
175

            
176
    #[tokio::test]
177
1
    async fn run_activity_report_missing_from_emits_error() {
178
1
        let err = run_activity_report(Uuid::nil(), None, Some("2026-01-01T00:00:00Z".into()))
179
1
            .await
180
            .unwrap_err();
181
1
        assert!(err.to_string().contains(":date-from"), "got: {err}");
182
1
    }
183

            
184
    #[tokio::test]
185
1
    async fn run_activity_report_invalid_date_emits_error() {
186
1
        let err = run_activity_report(Uuid::nil(), Some("nope".into()), Some("nope".into()))
187
1
            .await
188
            .unwrap_err();
189
1
        assert!(err.to_string().contains("invalid"), "got: {err}");
190
1
    }
191

            
192
    #[tokio::test]
193
1
    async fn run_category_breakdown_missing_from_emits_error() {
194
1
        let err = run_category_breakdown(Uuid::nil(), None, Some("2026-01-01T00:00:00Z".into()))
195
1
            .await
196
            .unwrap_err();
197
1
        assert!(err.to_string().contains(":date-from"), "got: {err}");
198
1
    }
199

            
200
    #[tokio::test]
201
1
    async fn run_category_breakdown_invalid_date_emits_error() {
202
1
        let err = run_category_breakdown(Uuid::nil(), Some("not-rfc3339".into()), Some("x".into()))
203
1
            .await
204
            .unwrap_err();
205
1
        assert!(err.to_string().contains("invalid"), "got: {err}");
206
1
    }
207

            
208
    #[test]
209
1
    fn format_balance_includes_all_commodity_amounts() {
210
1
        let node = ReportNode {
211
1
            account_id: Uuid::nil(),
212
1
            account_name: "Assets".to_string(),
213
1
            account_path: "Assets".to_string(),
214
1
            depth: 0,
215
1
            account_type: Some("asset".to_string()),
216
1
            amounts: vec![
217
1
                CommodityAmount {
218
1
                    commodity_id: Uuid::nil(),
219
1
                    commodity_symbol: "USD".to_string(),
220
1
                    amount: Rational64::new(100, 1),
221
1
                },
222
1
                CommodityAmount {
223
1
                    commodity_id: Uuid::nil(),
224
1
                    commodity_symbol: "EUR".to_string(),
225
1
                    amount: Rational64::new(50, 1),
226
1
                },
227
1
            ],
228
1
            own_amounts: vec![CommodityAmount {
229
1
                commodity_id: Uuid::nil(),
230
1
                commodity_symbol: "USD".to_string(),
231
1
                amount: Rational64::new(40, 1),
232
1
            }],
233
1
            children: vec![],
234
1
        };
235
1
        let data = ReportData {
236
1
            meta: ReportMeta {
237
1
                date_from: None,
238
1
                date_to: None,
239
1
                target_commodity_id: None,
240
1
            },
241
1
            periods: vec![PeriodData {
242
1
                label: None,
243
1
                roots: vec![node],
244
1
            }],
245
1
        };
246
1
        let s = format_balance(&data);
247
1
        assert!(s.contains(":symbol \"USD\""), "USD must appear: {s}");
248
1
        assert!(s.contains(":symbol \"EUR\""), "EUR must appear: {s}");
249
1
        assert!(
250
1
            s.contains(":balance-report :periods"),
251
            "top-level shape: {s}"
252
        );
253
1
        assert!(s.contains(":roots"), "must have :roots key: {s}");
254
1
        let (rolled, own) = s.split_once(":own-amounts").expect("own-amounts key");
255
1
        assert!(rolled.contains(":amount 100"), "roll-up first: {s}");
256
1
        assert!(
257
1
            own.contains(":amount 40") && !own.contains(":amount 100"),
258
            "{s}"
259
        );
260
1
    }
261
}