Skip to main content

rpc/forms/
options.rs

1//! The picker options of a form field.
2
3use std::collections::HashMap;
4
5use forms::Source;
6use server::artifact_mgmt::user::{ScriptInfo, TemplateInfo};
7use server::command::CmdResult;
8use server::command::account_commodities::ListAccountSingleCommodities;
9use server::command::template_list::ListTemplates;
10use server::script_state::is_enabled;
11use server::user::User;
12use uuid::Uuid;
13
14use super::Failure;
15use crate::option_labels::unique_labels;
16use crate::resolve::Directory;
17use crate::resolve::options::DirectorySource;
18pub use crate::resolve::options::FormOption;
19
20const CTX: &str = "form-options";
21
22/// The user's accounts, commodities or templates as picker options. An account
23/// holding exactly one commodity carries it as `commodity`; a template is
24/// labelled by its name, listed in the web's order.
25pub async fn options(user_id: Uuid, source: Source) -> Result<Vec<FormOption>, Failure> {
26    match source {
27        Source::Accounts => directory_options(user_id, DirectorySource::Accounts).await,
28        Source::Commodities => directory_options(user_id, DirectorySource::Commodities).await,
29        Source::Templates => templates(user_id).await,
30        Source::Scripts => scripts(user_id).await,
31    }
32}
33
34async fn directory_options(
35    user_id: Uuid,
36    source: DirectorySource,
37) -> Result<Vec<FormOption>, Failure> {
38    let directory = Directory::load(CTX, user_id).await?;
39    let mut options = directory.options(source);
40    if source == DirectorySource::Accounts {
41        let held = single_commodities(user_id).await?;
42        for option in &mut options {
43            option.commodity = held.get(&option.id).copied();
44        }
45    }
46    Ok(options)
47}
48
49async fn single_commodities(user_id: Uuid) -> Result<HashMap<Uuid, Uuid>, Failure> {
50    let held = ListAccountSingleCommodities::new()
51        .user_id(user_id)
52        .run()
53        .await
54        .map_err(|err| Failure::from_command(CTX, err))?;
55    match held {
56        Some(CmdResult::SingleCommodities(held)) => Ok(held),
57        other => Err(Failure::Internal(wasmtime::Error::msg(format!(
58            "form-options: unexpected result {other:?}"
59        )))),
60    }
61}
62
63async fn templates(user_id: Uuid) -> Result<Vec<FormOption>, Failure> {
64    let listed = ListTemplates::new()
65        .user_id(user_id)
66        .run()
67        .await
68        .map_err(|err| Failure::from_command(CTX, err))?;
69    match listed {
70        Some(CmdResult::Templates(listed)) => Ok(template_options(listed)),
71        other => Err(Failure::Internal(wasmtime::Error::msg(format!(
72            "form-options: unexpected result {other:?}"
73        )))),
74    }
75}
76
77async fn scripts(user_id: Uuid) -> Result<Vec<FormOption>, Failure> {
78    let listed = User { id: user_id }
79        .list_scripts()
80        .await
81        .map_err(|err| Failure::from_command(CTX, err.into()))?;
82    Ok(script_options(listed))
83}
84
85/// A script's state shows after its name: `tag-sync (disabled, no source)`.
86fn script_label(label: &str, script: &ScriptInfo) -> String {
87    let states: Vec<&str> = [
88        (!is_enabled(script.enabled.as_deref())).then_some("disabled"),
89        (!script.has_source).then_some("no source"),
90    ]
91    .into_iter()
92    .flatten()
93    .collect();
94    match states.is_empty() {
95        true => label.to_string(),
96        false => format!("{label} ({})", states.join(", ")),
97    }
98}
99
100fn script_options(listed: Vec<ScriptInfo>) -> Vec<FormOption> {
101    let names: Vec<(Uuid, Vec<String>)> = listed
102        .iter()
103        .map(|script| {
104            let name = script.name.as_deref().unwrap_or("unnamed");
105            (script.id, vec![name.to_string()])
106        })
107        .collect();
108    let labels = unique_labels(&names, str::to_string);
109    listed
110        .into_iter()
111        .zip(labels)
112        .map(|(script, label)| FormOption {
113            id: script.id,
114            label: script_label(&label, &script),
115            alias: label.clone(),
116            path: label,
117            commodity: None,
118        })
119        .collect()
120}
121
122fn template_options(listed: Vec<TemplateInfo>) -> Vec<FormOption> {
123    let names: Vec<(Uuid, Vec<String>)> = listed
124        .iter()
125        .map(|template| {
126            let name = template.name.as_deref().unwrap_or("unnamed");
127            (template.id, vec![name.to_string()])
128        })
129        .collect();
130    let labels = unique_labels(&names, str::to_string);
131    listed
132        .into_iter()
133        .zip(labels)
134        .map(|(template, label)| FormOption {
135            id: template.id,
136            alias: label.clone(),
137            path: label.clone(),
138            label,
139            commodity: None,
140        })
141        .collect()
142}