Skip to main content

rpc/forms/
template_test.rs

1//! `template-test`: a template source rendered against the user's data, never saved.
2
3use forms::{FormValues, TEMPLATE_TEST};
4use scripting::runtime::EvalValue;
5use uuid::Uuid;
6
7use super::Failure;
8use super::outcome::key;
9use super::transaction_create_load::template_values;
10use super::transaction_rows::error_at;
11use crate::ScriptCtx;
12use crate::draft::{DraftSplit, DraftTag, TransactionDraft};
13use crate::host_failure::unavailable_condition;
14use crate::template::{TemplateError, compile_template, render_template};
15
16/// What a test of a template produced: its draft and why the create form
17/// cannot be pre-filled from it, if it cannot.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct TemplateDraft {
20    pub draft: TransactionDraft,
21    pub refusal: Option<String>,
22}
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum Stage {
26    Compile,
27    Render,
28}
29
30impl Stage {
31    #[must_use]
32    pub const fn as_str(self) -> &'static str {
33        match self {
34            Self::Compile => "compile",
35            Self::Render => "render",
36        }
37    }
38}
39
40/// A template that did not get as far as a draft, and where it stopped.
41#[derive(Debug)]
42pub struct TestError {
43    pub stage: Stage,
44    pub error: TemplateError,
45}
46
47impl TestError {
48    fn compile(error: TemplateError) -> Self {
49        Self {
50            stage: Stage::Compile,
51            error,
52        }
53    }
54
55    fn render(error: TemplateError) -> Self {
56        Self {
57            stage: Stage::Render,
58            error,
59        }
60    }
61}
62
63fn refusal_of(draft: &TransactionDraft) -> Result<Option<String>, TemplateError> {
64    match template_values(draft) {
65        Ok(_) => Ok(None),
66        Err(Failure::Internal(err)) => Err(TemplateError::Host(err.to_string())),
67        Err(failure) => Ok(Some(failure.to_string())),
68    }
69}
70
71/// Compile and render `source` for `user_id`; the one path the `template-test`
72/// form and the web test endpoint share.
73///
74/// # Errors
75/// The stage and cause of a source that does not compile or render, or of a
76/// host failure.
77pub async fn template_draft(user_id: Uuid, source: &str) -> Result<TemplateDraft, TestError> {
78    compile_template(source).map_err(TestError::compile)?;
79    let draft = render_template(&ScriptCtx::new(user_id), source)
80        .await
81        .map_err(TestError::render)?;
82    let refusal = refusal_of(&draft).map_err(TestError::render)?;
83    Ok(TemplateDraft { draft, refusal })
84}
85
86fn failure(err: TestError) -> Failure {
87    match err.error {
88        TemplateError::Unavailable(message) => Failure::Internal(unavailable_condition(message)),
89        error if error.is_internal() => Failure::Internal(wasmtime::Error::msg(format!(
90            "{}: {error}",
91            TEMPLATE_TEST.name
92        ))),
93        error => error_at("source".to_string(), error.to_string()).into(),
94    }
95}
96
97/// The `template-test` query over `values`.
98///
99/// # Errors
100/// A field error at `source` when it does not compile or render.
101pub async fn test_template(user_id: Uuid, values: &FormValues) -> Result<TemplateDraft, Failure> {
102    let values = &values.normalized(&TEMPLATE_TEST);
103    let errors = values.check(&TEMPLATE_TEST);
104    if !errors.is_empty() {
105        return Err(errors.into());
106    }
107    let source = values.text("source").unwrap_or_default();
108    template_draft(user_id, source).await.map_err(failure)
109}
110
111fn text(value: &str) -> EvalValue {
112    EvalValue::String(value.to_string())
113}
114
115fn optional(value: Option<&str>) -> EvalValue {
116    value.map_or(EvalValue::Nil, text)
117}
118
119fn tag_value(tag: &DraftTag) -> EvalValue {
120    EvalValue::List(vec![
121        key("NAME"),
122        text(&tag.name),
123        key("VALUE"),
124        text(&tag.value),
125    ])
126}
127
128fn tags_value(tags: &[DraftTag]) -> EvalValue {
129    EvalValue::List(tags.iter().map(tag_value).collect())
130}
131
132fn amount_text(split: &DraftSplit) -> String {
133    amount::wire_rational(num_rational::Rational64::new_raw(
134        split.value_num,
135        split.value_denom,
136    ))
137}
138
139fn split_value(split: &DraftSplit) -> EvalValue {
140    EvalValue::List(vec![
141        key("ACCOUNT"),
142        text(&split.account_id),
143        key("AMOUNT"),
144        text(&amount_text(split)),
145        key("COMMODITY"),
146        text(&split.commodity_id),
147        key("TAGS"),
148        tags_value(&split.tags),
149    ])
150}
151
152impl TemplateDraft {
153    /// `(:NOTE … :DATE … :SPLITS ((:ACCOUNT … :AMOUNT … :COMMODITY … :TAGS ((:NAME … :VALUE …) …)) …)
154    /// :TAGS ((:NAME … :VALUE …) …) :PREFILLABLE t|nil :REASON … )`; an unset note, date or reason is `nil`.
155    pub(super) fn to_value(&self) -> EvalValue {
156        let draft = &self.draft;
157        EvalValue::List(vec![
158            key("NOTE"),
159            optional(draft.note.as_deref()),
160            key("DATE"),
161            optional(draft.date.as_deref()),
162            key("SPLITS"),
163            EvalValue::List(draft.splits.iter().map(split_value).collect()),
164            key("TAGS"),
165            tags_value(&draft.tags),
166            key("PREFILLABLE"),
167            if self.refusal.is_none() {
168                EvalValue::T
169            } else {
170                EvalValue::Nil
171            },
172            key("REASON"),
173            optional(self.refusal.as_deref()),
174        ])
175    }
176}