1
//! Client-contract natives: descriptors, picker options and form submit.
2

            
3
use forms::{
4
    ACCOUNT_MERGE, Form, FormValues, Source, Suggest, descriptor_sexpr, descriptors_sexpr,
5
    escape_str, write_payload,
6
};
7
use scripting::runtime::EvalValue;
8
use uuid::Uuid;
9

            
10
use super::{args_error, counted, form_invalid, native_failure, run_transaction_query};
11
use crate::forms::{
12
    Failure, FormAction, FormOption, FormOutcome, Handler, Outcome, ReportOutcome, Suggestion,
13
    convert, form_named, load_noticed, merge_preview, options, parse_payload, record_form_request,
14
    set_config, submit, submit_noticed, suggestions, test_template, typed_report,
15
};
16

            
17
/// One descriptor by name, or all of them for the empty name.
18
483
pub fn form_descriptor(name: &str) -> wasmtime::Result<String> {
19
483
    if name.is_empty() {
20
481
        return Ok(descriptors_sexpr(forms::all()));
21
2
    }
22
2
    form_named(name)
23
2
        .map(descriptor_sexpr)
24
2
        .map_err(native_failure)
25
483
}
26

            
27
34739
fn source(name: &str) -> wasmtime::Result<Source> {
28
34739
    Source::by_name(name).ok_or_else(|| args_error(format!("unknown option source '{name}'")))
29
34739
}
30

            
31
63565
fn option_sexpr(option: &FormOption) -> String {
32
63565
    let commodity = option
33
63565
        .commodity
34
14411
        .map(|id| format!(" :commodity {}", escape_str(&id.to_string())))
35
        .unwrap_or_default();
36
63565
    format!(
37
63565
        "(:id {} :label {} :alias {}{commodity})",
38
63565
        escape_str(&option.id.to_string()),
39
63565
        escape_str(&option.label),
40
63565
        escape_str(&option.alias)
41
    )
42
63565
}
43

            
44
/// The user's accounts or commodities as picker options, or a text cell's
45
/// suggestions as a list of strings. A suggestion source that takes a tag name
46
/// carries it after a colon: `split-tag-values:Category`.
47
35087
pub async fn form_options(user_id: Uuid, name: &str) -> wasmtime::Result<String> {
48
35087
    if let Some(request) = suggest_request(name)? {
49
346
        let strings = suggestions(user_id, &request)
50
346
            .await
51
1
            .map_err(|err| native_failure(Failure::from_command("form-options", err.into())))?;
52
345
        let items: Vec<String> = strings.iter().map(|text| escape_str(text)).collect();
53
345
        return Ok(format!("({})", items.join(" ")));
54
34739
    }
55
34739
    let options = options(user_id, source(name)?)
56
34739
        .await
57
34735
        .map_err(native_failure)?;
58
34735
    let items: Vec<String> = options.iter().map(option_sexpr).collect();
59
34735
    Ok(format!("({})", items.join(" ")))
60
35087
}
61

            
62
/// The suggestion `name` asks for, `None` for a picker source. The tag name
63
/// is everything after the first colon.
64
35087
fn suggest_request(name: &str) -> wasmtime::Result<Option<Suggestion>> {
65
35087
    let (head, tag) = match name.split_once(':') {
66
181
        Some((head, tag)) => (head, Some(tag)),
67
34906
        None => (name, None),
68
    };
69
35087
    let Some(suggest) = Suggest::by_name(head) else {
70
34739
        return Ok(None);
71
    };
72
348
    Suggestion::of(suggest, tag).map(Some).map_err(args_error)
73
35087
}
74

            
75
11965
async fn loaded(user_id: Uuid, name: &str, id: &str) -> Result<(String, Option<String>), Failure> {
76
11965
    let form = form_named(name)?;
77
11963
    let (values, notice) = load_noticed(user_id, form, id).await?;
78
11464
    Ok((write_payload(form, &values), notice))
79
11965
}
80

            
81
/// Load the values of a form over the compiled-in form names.
82
125
pub async fn load_form(user_id: Uuid, name: &str, id: &str) -> wasmtime::Result<String> {
83
125
    load_form_noticed(user_id, name, id)
84
125
        .await
85
        .map(|(text, _)| text)
86
125
}
87

            
88
/// [`load_form`] and the notice the loaded entity carries.
89
11965
pub async fn load_form_noticed(
90
11965
    user_id: Uuid,
91
11965
    name: &str,
92
11965
    id: &str,
93
11965
) -> wasmtime::Result<(String, Option<String>)> {
94
11965
    counted(name, FormAction::Load, loaded(user_id, name, id).await)
95
11965
}
96

            
97
46923
fn dispatch(name: &str) -> Result<(&'static Form, Handler), Failure> {
98
46923
    let form = form_named(name)?;
99
46917
    Ok((form, Handler::of(form)?))
100
46923
}
101

            
102
/// The payload as values; one that does not read counts as malformed.
103
42412
fn decoded(form: &Form, action: FormAction, payload: &str) -> wasmtime::Result<FormValues> {
104
42412
    parse_payload(form, payload).map_err(|error| {
105
167
        record_form_request(form.name, action, FormOutcome::Malformed);
106
167
        form_invalid(&[error])
107
167
    })
108
42412
}
109

            
110
/// The report of the query form `form` over `payload`; the one path `submit-form` and
111
/// `report-chart` share.
112
8528
async fn report_values(
113
8528
    user_id: Uuid,
114
8528
    form: &Form,
115
8528
    payload: &str,
116
8528
) -> wasmtime::Result<ReportOutcome> {
117
8528
    let values = decoded(form, FormAction::Query, payload)?;
118
8526
    counted(
119
8526
        form.name,
120
8526
        FormAction::Query,
121
8526
        typed_report(user_id, form, &values).await,
122
    )
123
8528
}
124

            
125
/// The outcome of the report form `name` over `payload`, as `submit-form` runs it.
126
///
127
/// # Errors
128
/// An unknown or non-report form (the latter is not counted), an unreadable payload or invalid values.
129
7241
pub async fn report_outcome(
130
7241
    user_id: Uuid,
131
7241
    name: &str,
132
7241
    payload: &str,
133
7241
) -> wasmtime::Result<ReportOutcome> {
134
7241
    match dispatch(name) {
135
        Ok((form, Handler::ReportBalance | Handler::ReportActivity | Handler::ReportCategory)) => {
136
7234
            report_values(user_id, form, payload).await
137
        }
138
5
        Ok(_) => Err(args_error(format!(
139
5
            "report-chart: '{name}' is not a report form"
140
5
        ))),
141
2
        Err(failure) => counted(name, FormAction::Submit, Err(failure)),
142
    }
143
7241
}
144

            
145
/// Dispatch a submit over the compiled-in form names.
146
5080
pub async fn submit_form(user_id: Uuid, name: &str, payload: &str) -> wasmtime::Result<EvalValue> {
147
5080
    let (form, handler) = match dispatch(name) {
148
5078
        Ok(dispatched) => dispatched,
149
2
        Err(failure) => return counted(name, FormAction::Submit, Err(failure)),
150
    };
151
5078
    match handler {
152
        Handler::TransactionQuery => {
153
1777
            let values = decoded(form, FormAction::Query, payload)?;
154
1777
            run_transaction_query(user_id, &values).await
155
        }
156
        Handler::ReportBalance | Handler::ReportActivity | Handler::ReportCategory => {
157
1294
            Outcome::from(report_values(user_id, form, payload).await?).to_value()
158
        }
159
        Handler::Convert => {
160
483
            let values = decoded(form, FormAction::Query, payload)?;
161
483
            let converted = convert(user_id, &values).await;
162
483
            Outcome::Value(counted(form.name, FormAction::Query, converted)?).to_value()
163
        }
164
        Handler::TemplateTest => {
165
481
            let values = decoded(form, FormAction::Query, payload)?;
166
481
            let tested = test_template(user_id, &values).await;
167
481
            Outcome::Draft(counted(form.name, FormAction::Query, tested)?).to_value()
168
        }
169
        Handler::ConfigSet => {
170
642
            let values = decoded(form, FormAction::Submit, payload)?;
171
642
            let stored = set_config(user_id, &values).await;
172
642
            counted(form.name, FormAction::Submit, stored)?;
173
482
            Outcome::Done.to_value()
174
        }
175
        Handler::TransactionCreate
176
        | Handler::TransactionEdit
177
        | Handler::AccountMerge
178
        | Handler::AccountCreate
179
        | Handler::AccountEdit
180
        | Handler::CommodityCreate
181
        | Handler::CommodityEdit
182
        | Handler::TagCreate
183
        | Handler::TagEdit
184
        | Handler::TemplateCreate
185
        | Handler::TemplateEdit
186
        | Handler::ScriptCreate
187
        | Handler::ScriptEdit
188
        | Handler::SshKeyAdd => {
189
401
            let values = decoded(form, FormAction::Submit, payload)?;
190
237
            let submitted = submit(user_id, form, &values).await;
191
237
            let submitted = counted(form.name, FormAction::Submit, submitted)?;
192
182
            Outcome::Entity(submitted.id).to_value()
193
        }
194
    }
195
4920
}
196

            
197
/// [`submit_form`] and the notice its reply carries.
198
34602
pub async fn submit_form_noticed(
199
34602
    user_id: Uuid,
200
34602
    name: &str,
201
34602
    payload: &str,
202
34602
) -> wasmtime::Result<(EvalValue, Option<String>)> {
203
34602
    let (form, handler) = match dispatch(name) {
204
34600
        Ok(dispatched) => dispatched,
205
2
        Err(failure) => return counted(name, FormAction::Submit, Err(failure)),
206
    };
207
34600
    if !handler.yields_entity() {
208
4666
        return Ok((submit_form(user_id, name, payload).await?, None));
209
29934
    }
210
29934
    let values = decoded(form, FormAction::Submit, payload)?;
211
29934
    let submitted = submit_noticed(user_id, form, &values).await;
212
29934
    let (submitted, notice) = counted(form.name, FormAction::Submit, submitted)?;
213
25930
    Ok((Outcome::Entity(submitted.id).to_value()?, notice))
214
34442
}
215

            
216
/// The accounts a merge payload picks and the splits the merge would move.
217
166
pub async fn merge_preview_value(user_id: Uuid, payload: &str) -> wasmtime::Result<EvalValue> {
218
166
    let values = decoded(&ACCOUNT_MERGE, FormAction::Query, payload)?;
219
165
    let previewed = merge_preview(user_id, &values).await;
220
165
    counted(ACCOUNT_MERGE.name, FormAction::Query, previewed)?.to_value()
221
166
}