1
//! `template-test`: a template source rendered against the user's data, never saved.
2

            
3
use forms::{FormValues, TEMPLATE_TEST};
4
use scripting::runtime::EvalValue;
5
use uuid::Uuid;
6

            
7
use super::Failure;
8
use super::outcome::key;
9
use super::transaction_create_load::template_values;
10
use super::transaction_rows::error_at;
11
use crate::ScriptCtx;
12
use crate::draft::{DraftSplit, DraftTag, TransactionDraft};
13
use crate::host_failure::unavailable_condition;
14
use 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)]
19
pub struct TemplateDraft {
20
    pub draft: TransactionDraft,
21
    pub refusal: Option<String>,
22
}
23

            
24
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25
pub enum Stage {
26
    Compile,
27
    Render,
28
}
29

            
30
impl 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)]
42
pub struct TestError {
43
    pub stage: Stage,
44
    pub error: TemplateError,
45
}
46

            
47
impl TestError {
48
321
    fn compile(error: TemplateError) -> Self {
49
321
        Self {
50
321
            stage: Stage::Compile,
51
321
            error,
52
321
        }
53
321
    }
54

            
55
321
    fn render(error: TemplateError) -> Self {
56
321
        Self {
57
321
            stage: Stage::Render,
58
321
            error,
59
321
        }
60
321
    }
61
}
62

            
63
1923
fn refusal_of(draft: &TransactionDraft) -> Result<Option<String>, TemplateError> {
64
1923
    match template_values(draft) {
65
1282
        Ok(_) => Ok(None),
66
        Err(Failure::Internal(err)) => Err(TemplateError::Host(err.to_string())),
67
641
        Err(failure) => Ok(Some(failure.to_string())),
68
    }
69
1923
}
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.
77
2565
pub async fn template_draft(user_id: Uuid, source: &str) -> Result<TemplateDraft, TestError> {
78
2565
    compile_template(source).map_err(TestError::compile)?;
79
2244
    let draft = render_template(&ScriptCtx::new(user_id), source)
80
2244
        .await
81
2244
        .map_err(TestError::render)?;
82
1923
    let refusal = refusal_of(&draft).map_err(TestError::render)?;
83
1923
    Ok(TemplateDraft { draft, refusal })
84
2565
}
85

            
86
642
fn failure(err: TestError) -> Failure {
87
642
    match err.error {
88
160
        TemplateError::Unavailable(message) => Failure::Internal(unavailable_condition(message)),
89
482
        error if error.is_internal() => Failure::Internal(wasmtime::Error::msg(format!(
90
            "{}: {error}",
91
            TEMPLATE_TEST.name
92
        ))),
93
482
        error => error_at("source".to_string(), error.to_string()).into(),
94
    }
95
642
}
96

            
97
/// The `template-test` query over `values`.
98
///
99
/// # Errors
100
/// A field error at `source` when it does not compile or render.
101
2726
pub async fn test_template(user_id: Uuid, values: &FormValues) -> Result<TemplateDraft, Failure> {
102
2726
    let values = &values.normalized(&TEMPLATE_TEST);
103
2726
    let errors = values.check(&TEMPLATE_TEST);
104
2726
    if !errors.is_empty() {
105
161
        return Err(errors.into());
106
2565
    }
107
2565
    let source = values.text("source").unwrap_or_default();
108
2565
    template_draft(user_id, source).await.map_err(failure)
109
2726
}
110

            
111
2572
fn text(value: &str) -> EvalValue {
112
2572
    EvalValue::String(value.to_string())
113
2572
}
114

            
115
963
fn optional(value: Option<&str>) -> EvalValue {
116
963
    value.map_or(EvalValue::Nil, text)
117
963
}
118

            
119
322
fn tag_value(tag: &DraftTag) -> EvalValue {
120
322
    EvalValue::List(vec![
121
322
        key("NAME"),
122
322
        text(&tag.name),
123
322
        key("VALUE"),
124
322
        text(&tag.value),
125
322
    ])
126
322
}
127

            
128
803
fn tags_value(tags: &[DraftTag]) -> EvalValue {
129
803
    EvalValue::List(tags.iter().map(tag_value).collect())
130
803
}
131

            
132
482
fn amount_text(split: &DraftSplit) -> String {
133
482
    amount::wire_rational(num_rational::Rational64::new_raw(
134
482
        split.value_num,
135
482
        split.value_denom,
136
482
    ))
137
482
}
138

            
139
482
fn split_value(split: &DraftSplit) -> EvalValue {
140
482
    EvalValue::List(vec![
141
482
        key("ACCOUNT"),
142
482
        text(&split.account_id),
143
482
        key("AMOUNT"),
144
482
        text(&amount_text(split)),
145
482
        key("COMMODITY"),
146
482
        text(&split.commodity_id),
147
482
        key("TAGS"),
148
482
        tags_value(&split.tags),
149
482
    ])
150
482
}
151

            
152
impl 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
321
    pub(super) fn to_value(&self) -> EvalValue {
156
321
        let draft = &self.draft;
157
321
        EvalValue::List(vec![
158
321
            key("NOTE"),
159
321
            optional(draft.note.as_deref()),
160
321
            key("DATE"),
161
321
            optional(draft.date.as_deref()),
162
321
            key("SPLITS"),
163
321
            EvalValue::List(draft.splits.iter().map(split_value).collect()),
164
321
            key("TAGS"),
165
321
            tags_value(&draft.tags),
166
321
            key("PREFILLABLE"),
167
321
            if self.refusal.is_none() {
168
161
                EvalValue::T
169
            } else {
170
160
                EvalValue::Nil
171
            },
172
321
            key("REASON"),
173
321
            optional(self.refusal.as_deref()),
174
        ])
175
321
    }
176
}