1
//! A submit's result and the one value built from it.
2

            
3
use chrono::SecondsFormat;
4
use num_rational::Rational64;
5
use scripting::runtime::EvalValue;
6
use server::command::{ActivityData, BreakdownData, ReportData};
7
use uuid::Uuid;
8

            
9
use super::report_format::{format_activity_text, format_balance, format_breakdown};
10
use super::{QueryPage, QueryRow, TemplateDraft};
11

            
12
#[derive(Debug, Clone, PartialEq, Eq)]
13
pub enum Outcome {
14
    /// A mutation's stored entity.
15
    Entity(Uuid),
16
    /// A mutation without an entity to report.
17
    Done,
18
    /// The `convert` form's amount in the target commodity.
19
    Value(Rational64),
20
    /// A query form's page.
21
    Page(QueryPage),
22
    /// The `report-balance` form's report.
23
    Balance(ReportData),
24
    /// The `report-activity` form's report.
25
    Activity(ActivityData),
26
    /// The `report-category` form's report.
27
    Breakdown(BreakdownData),
28
    /// The `template-test` form's rendered draft.
29
    Draft(TemplateDraft),
30
}
31

            
32
/// The result of a report form: the three outcomes a chart can be drawn from.
33
#[derive(Debug, Clone, PartialEq, Eq)]
34
pub enum ReportOutcome {
35
    Balance(ReportData),
36
    Activity(ActivityData),
37
    Breakdown(BreakdownData),
38
}
39

            
40
impl From<ReportOutcome> for Outcome {
41
13019
    fn from(report: ReportOutcome) -> Self {
42
13019
        match report {
43
3861
            ReportOutcome::Balance(data) => Self::Balance(data),
44
3536
            ReportOutcome::Activity(data) => Self::Activity(data),
45
5622
            ReportOutcome::Breakdown(data) => Self::Breakdown(data),
46
        }
47
13019
    }
48
}
49

            
50
impl Outcome {
51
    /// What `submit-form` returns: the UUID string, `t` for a mutation without an entity, the convert ratio as a number, the page plist
52
    /// `(:rows ((:id … :date … :date-text … :note … :amount …) …) :has-more t|nil :total n)` as a list with
53
    /// keyword keys, a report's plist text (see `format_balance`), or the template draft plist (see `TemplateDraft::to_value`).
54
    ///
55
    /// # Errors
56
    /// A page total beyond `i32`.
57
30006
    pub fn to_value(&self) -> wasmtime::Result<EvalValue> {
58
30006
        match self {
59
26113
            Self::Entity(id) => Ok(EvalValue::String(id.to_string())),
60
483
            Self::Done => Ok(EvalValue::T),
61
164
            Self::Value(ratio) => Ok(EvalValue::Ratio {
62
164
                numer: *ratio.numer(),
63
164
                denom: *ratio.denom(),
64
164
            }),
65
1636
            Self::Page(page) => page_value(page),
66
805
            Self::Balance(data) => Ok(EvalValue::String(format_balance(data))),
67
322
            Self::Activity(data) => format_activity_text(data).map(EvalValue::String),
68
162
            Self::Breakdown(data) => Ok(EvalValue::String(format_breakdown(data))),
69
321
            Self::Draft(draft) => Ok(draft.to_value()),
70
        }
71
30006
    }
72
}
73

            
74
62097
pub(crate) fn key(name: &str) -> EvalValue {
75
62097
    EvalValue::Symbol(format!(":{name}"))
76
62097
}
77

            
78
39405
fn text(value: &str) -> EvalValue {
79
39405
    EvalValue::String(value.to_string())
80
39405
}
81

            
82
7881
fn row_value(row: &QueryRow) -> EvalValue {
83
7881
    EvalValue::List(vec![
84
7881
        key("ID"),
85
7881
        text(&row.id.to_string()),
86
7881
        key("DATE"),
87
7881
        text(&row.date.to_rfc3339_opts(SecondsFormat::AutoSi, true)),
88
7881
        key("DATE-TEXT"),
89
7881
        text(&row.date_text),
90
7881
        key("NOTE"),
91
7881
        text(&row.note),
92
7881
        key("AMOUNT"),
93
7881
        text(&row.amount),
94
7881
    ])
95
7881
}
96

            
97
1636
fn page_value(page: &QueryPage) -> wasmtime::Result<EvalValue> {
98
1636
    let total = i32::try_from(page.total)
99
1
        .map_err(|_| wasmtime::Error::msg(format!("page total {} exceeds i32", page.total)))?;
100
1635
    Ok(EvalValue::List(vec![
101
1635
        key("ROWS"),
102
1635
        EvalValue::List(page.rows.iter().map(row_value).collect()),
103
1635
        key("HAS-MORE"),
104
1635
        if page.has_more {
105
330
            EvalValue::T
106
        } else {
107
1305
            EvalValue::Nil
108
        },
109
1635
        key("TOTAL"),
110
1635
        EvalValue::I32(total),
111
    ]))
112
1636
}