Skip to main content

rpc/forms/
outcome.rs

1//! A submit's result and the one value built from it.
2
3use chrono::SecondsFormat;
4use num_rational::Rational64;
5use scripting::runtime::EvalValue;
6use server::command::{ActivityData, BreakdownData, ReportData};
7use uuid::Uuid;
8
9use super::report_format::{format_activity_text, format_balance, format_breakdown};
10use super::{QueryPage, QueryRow, TemplateDraft};
11
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub 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)]
34pub enum ReportOutcome {
35    Balance(ReportData),
36    Activity(ActivityData),
37    Breakdown(BreakdownData),
38}
39
40impl From<ReportOutcome> for Outcome {
41    fn from(report: ReportOutcome) -> Self {
42        match report {
43            ReportOutcome::Balance(data) => Self::Balance(data),
44            ReportOutcome::Activity(data) => Self::Activity(data),
45            ReportOutcome::Breakdown(data) => Self::Breakdown(data),
46        }
47    }
48}
49
50impl 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    pub fn to_value(&self) -> wasmtime::Result<EvalValue> {
58        match self {
59            Self::Entity(id) => Ok(EvalValue::String(id.to_string())),
60            Self::Done => Ok(EvalValue::T),
61            Self::Value(ratio) => Ok(EvalValue::Ratio {
62                numer: *ratio.numer(),
63                denom: *ratio.denom(),
64            }),
65            Self::Page(page) => page_value(page),
66            Self::Balance(data) => Ok(EvalValue::String(format_balance(data))),
67            Self::Activity(data) => format_activity_text(data).map(EvalValue::String),
68            Self::Breakdown(data) => Ok(EvalValue::String(format_breakdown(data))),
69            Self::Draft(draft) => Ok(draft.to_value()),
70        }
71    }
72}
73
74pub(crate) fn key(name: &str) -> EvalValue {
75    EvalValue::Symbol(format!(":{name}"))
76}
77
78fn text(value: &str) -> EvalValue {
79    EvalValue::String(value.to_string())
80}
81
82fn row_value(row: &QueryRow) -> EvalValue {
83    EvalValue::List(vec![
84        key("ID"),
85        text(&row.id.to_string()),
86        key("DATE"),
87        text(&row.date.to_rfc3339_opts(SecondsFormat::AutoSi, true)),
88        key("DATE-TEXT"),
89        text(&row.date_text),
90        key("NOTE"),
91        text(&row.note),
92        key("AMOUNT"),
93        text(&row.amount),
94    ])
95}
96
97fn page_value(page: &QueryPage) -> wasmtime::Result<EvalValue> {
98    let total = i32::try_from(page.total)
99        .map_err(|_| wasmtime::Error::msg(format!("page total {} exceeds i32", page.total)))?;
100    Ok(EvalValue::List(vec![
101        key("ROWS"),
102        EvalValue::List(page.rows.iter().map(row_value).collect()),
103        key("HAS-MORE"),
104        if page.has_more {
105            EvalValue::T
106        } else {
107            EvalValue::Nil
108        },
109        key("TOTAL"),
110        EvalValue::I32(total),
111    ]))
112}