Skip to main content

rpc/natives/forms/
client.rs

1//! Client-contract natives: descriptors, picker options and form submit.
2
3use forms::{
4    ACCOUNT_MERGE, Form, FormValues, Source, Suggest, descriptor_sexpr, descriptors_sexpr,
5    escape_str, write_payload,
6};
7use scripting::runtime::EvalValue;
8use uuid::Uuid;
9
10use super::{args_error, counted, form_invalid, native_failure, run_transaction_query};
11use 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.
18pub fn form_descriptor(name: &str) -> wasmtime::Result<String> {
19    if name.is_empty() {
20        return Ok(descriptors_sexpr(forms::all()));
21    }
22    form_named(name)
23        .map(descriptor_sexpr)
24        .map_err(native_failure)
25}
26
27fn source(name: &str) -> wasmtime::Result<Source> {
28    Source::by_name(name).ok_or_else(|| args_error(format!("unknown option source '{name}'")))
29}
30
31fn option_sexpr(option: &FormOption) -> String {
32    let commodity = option
33        .commodity
34        .map(|id| format!(" :commodity {}", escape_str(&id.to_string())))
35        .unwrap_or_default();
36    format!(
37        "(:id {} :label {} :alias {}{commodity})",
38        escape_str(&option.id.to_string()),
39        escape_str(&option.label),
40        escape_str(&option.alias)
41    )
42}
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`.
47pub async fn form_options(user_id: Uuid, name: &str) -> wasmtime::Result<String> {
48    if let Some(request) = suggest_request(name)? {
49        let strings = suggestions(user_id, &request)
50            .await
51            .map_err(|err| native_failure(Failure::from_command("form-options", err.into())))?;
52        let items: Vec<String> = strings.iter().map(|text| escape_str(text)).collect();
53        return Ok(format!("({})", items.join(" ")));
54    }
55    let options = options(user_id, source(name)?)
56        .await
57        .map_err(native_failure)?;
58    let items: Vec<String> = options.iter().map(option_sexpr).collect();
59    Ok(format!("({})", items.join(" ")))
60}
61
62/// The suggestion `name` asks for, `None` for a picker source. The tag name
63/// is everything after the first colon.
64fn suggest_request(name: &str) -> wasmtime::Result<Option<Suggestion>> {
65    let (head, tag) = match name.split_once(':') {
66        Some((head, tag)) => (head, Some(tag)),
67        None => (name, None),
68    };
69    let Some(suggest) = Suggest::by_name(head) else {
70        return Ok(None);
71    };
72    Suggestion::of(suggest, tag).map(Some).map_err(args_error)
73}
74
75async fn loaded(user_id: Uuid, name: &str, id: &str) -> Result<(String, Option<String>), Failure> {
76    let form = form_named(name)?;
77    let (values, notice) = load_noticed(user_id, form, id).await?;
78    Ok((write_payload(form, &values), notice))
79}
80
81/// Load the values of a form over the compiled-in form names.
82pub async fn load_form(user_id: Uuid, name: &str, id: &str) -> wasmtime::Result<String> {
83    load_form_noticed(user_id, name, id)
84        .await
85        .map(|(text, _)| text)
86}
87
88/// [`load_form`] and the notice the loaded entity carries.
89pub async fn load_form_noticed(
90    user_id: Uuid,
91    name: &str,
92    id: &str,
93) -> wasmtime::Result<(String, Option<String>)> {
94    counted(name, FormAction::Load, loaded(user_id, name, id).await)
95}
96
97fn dispatch(name: &str) -> Result<(&'static Form, Handler), Failure> {
98    let form = form_named(name)?;
99    Ok((form, Handler::of(form)?))
100}
101
102/// The payload as values; one that does not read counts as malformed.
103fn decoded(form: &Form, action: FormAction, payload: &str) -> wasmtime::Result<FormValues> {
104    parse_payload(form, payload).map_err(|error| {
105        record_form_request(form.name, action, FormOutcome::Malformed);
106        form_invalid(&[error])
107    })
108}
109
110/// The report of the query form `form` over `payload`; the one path `submit-form` and
111/// `report-chart` share.
112async fn report_values(
113    user_id: Uuid,
114    form: &Form,
115    payload: &str,
116) -> wasmtime::Result<ReportOutcome> {
117    let values = decoded(form, FormAction::Query, payload)?;
118    counted(
119        form.name,
120        FormAction::Query,
121        typed_report(user_id, form, &values).await,
122    )
123}
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.
129pub async fn report_outcome(
130    user_id: Uuid,
131    name: &str,
132    payload: &str,
133) -> wasmtime::Result<ReportOutcome> {
134    match dispatch(name) {
135        Ok((form, Handler::ReportBalance | Handler::ReportActivity | Handler::ReportCategory)) => {
136            report_values(user_id, form, payload).await
137        }
138        Ok(_) => Err(args_error(format!(
139            "report-chart: '{name}' is not a report form"
140        ))),
141        Err(failure) => counted(name, FormAction::Submit, Err(failure)),
142    }
143}
144
145/// Dispatch a submit over the compiled-in form names.
146pub async fn submit_form(user_id: Uuid, name: &str, payload: &str) -> wasmtime::Result<EvalValue> {
147    let (form, handler) = match dispatch(name) {
148        Ok(dispatched) => dispatched,
149        Err(failure) => return counted(name, FormAction::Submit, Err(failure)),
150    };
151    match handler {
152        Handler::TransactionQuery => {
153            let values = decoded(form, FormAction::Query, payload)?;
154            run_transaction_query(user_id, &values).await
155        }
156        Handler::ReportBalance | Handler::ReportActivity | Handler::ReportCategory => {
157            Outcome::from(report_values(user_id, form, payload).await?).to_value()
158        }
159        Handler::Convert => {
160            let values = decoded(form, FormAction::Query, payload)?;
161            let converted = convert(user_id, &values).await;
162            Outcome::Value(counted(form.name, FormAction::Query, converted)?).to_value()
163        }
164        Handler::TemplateTest => {
165            let values = decoded(form, FormAction::Query, payload)?;
166            let tested = test_template(user_id, &values).await;
167            Outcome::Draft(counted(form.name, FormAction::Query, tested)?).to_value()
168        }
169        Handler::ConfigSet => {
170            let values = decoded(form, FormAction::Submit, payload)?;
171            let stored = set_config(user_id, &values).await;
172            counted(form.name, FormAction::Submit, stored)?;
173            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            let values = decoded(form, FormAction::Submit, payload)?;
190            let submitted = submit(user_id, form, &values).await;
191            let submitted = counted(form.name, FormAction::Submit, submitted)?;
192            Outcome::Entity(submitted.id).to_value()
193        }
194    }
195}
196
197/// [`submit_form`] and the notice its reply carries.
198pub async fn submit_form_noticed(
199    user_id: Uuid,
200    name: &str,
201    payload: &str,
202) -> wasmtime::Result<(EvalValue, Option<String>)> {
203    let (form, handler) = match dispatch(name) {
204        Ok(dispatched) => dispatched,
205        Err(failure) => return counted(name, FormAction::Submit, Err(failure)),
206    };
207    if !handler.yields_entity() {
208        return Ok((submit_form(user_id, name, payload).await?, None));
209    }
210    let values = decoded(form, FormAction::Submit, payload)?;
211    let submitted = submit_noticed(user_id, form, &values).await;
212    let (submitted, notice) = counted(form.name, FormAction::Submit, submitted)?;
213    Ok((Outcome::Entity(submitted.id).to_value()?, notice))
214}
215
216/// The accounts a merge payload picks and the splits the merge would move.
217pub async fn merge_preview_value(user_id: Uuid, payload: &str) -> wasmtime::Result<EvalValue> {
218    let values = decoded(&ACCOUNT_MERGE, FormAction::Query, payload)?;
219    let previewed = merge_preview(user_id, &values).await;
220    counted(ACCOUNT_MERGE.name, FormAction::Query, previewed)?.to_value()
221}