1
//! The picker options of a form field.
2

            
3
use std::collections::HashMap;
4

            
5
use forms::Source;
6
use server::artifact_mgmt::user::{ScriptInfo, TemplateInfo};
7
use server::command::CmdResult;
8
use server::command::account_commodities::ListAccountSingleCommodities;
9
use server::command::template_list::ListTemplates;
10
use server::script_state::is_enabled;
11
use server::user::User;
12
use uuid::Uuid;
13

            
14
use super::Failure;
15
use crate::option_labels::unique_labels;
16
use crate::resolve::Directory;
17
use crate::resolve::options::DirectorySource;
18
pub use crate::resolve::options::FormOption;
19

            
20
const 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.
25
147068
pub async fn options(user_id: Uuid, source: Source) -> Result<Vec<FormOption>, Failure> {
26
147068
    match source {
27
75055
        Source::Accounts => directory_options(user_id, DirectorySource::Accounts).await,
28
70245
        Source::Commodities => directory_options(user_id, DirectorySource::Commodities).await,
29
1764
        Source::Templates => templates(user_id).await,
30
4
        Source::Scripts => scripts(user_id).await,
31
    }
32
147068
}
33

            
34
145300
async fn directory_options(
35
145300
    user_id: Uuid,
36
145300
    source: DirectorySource,
37
145300
) -> Result<Vec<FormOption>, Failure> {
38
145300
    let directory = Directory::load(CTX, user_id).await?;
39
144979
    let mut options = directory.options(source);
40
144979
    if source == DirectorySource::Accounts {
41
74734
        let held = single_commodities(user_id).await?;
42
74734
        for option in &mut options {
43
148370
            option.commodity = held.get(&option.id).copied();
44
        }
45
70245
    }
46
144979
    Ok(options)
47
145300
}
48

            
49
74734
async fn single_commodities(user_id: Uuid) -> Result<HashMap<Uuid, Uuid>, Failure> {
50
74734
    let held = ListAccountSingleCommodities::new()
51
74734
        .user_id(user_id)
52
74734
        .run()
53
74734
        .await
54
        .map_err(|err| Failure::from_command(CTX, err))?;
55
74734
    match held {
56
74734
        Some(CmdResult::SingleCommodities(held)) => Ok(held),
57
        other => Err(Failure::Internal(wasmtime::Error::msg(format!(
58
            "form-options: unexpected result {other:?}"
59
        )))),
60
    }
61
74734
}
62

            
63
1764
async fn templates(user_id: Uuid) -> Result<Vec<FormOption>, Failure> {
64
1764
    let listed = ListTemplates::new()
65
1764
        .user_id(user_id)
66
1764
        .run()
67
1764
        .await
68
        .map_err(|err| Failure::from_command(CTX, err))?;
69
1764
    match listed {
70
1764
        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
1764
}
76

            
77
4
async fn scripts(user_id: Uuid) -> Result<Vec<FormOption>, Failure> {
78
4
    let listed = User { id: user_id }
79
4
        .list_scripts()
80
4
        .await
81
        .map_err(|err| Failure::from_command(CTX, err.into()))?;
82
4
    Ok(script_options(listed))
83
4
}
84

            
85
/// A script's state shows after its name: `tag-sync (disabled, no source)`.
86
9
fn script_label(label: &str, script: &ScriptInfo) -> String {
87
9
    let states: Vec<&str> = [
88
9
        (!is_enabled(script.enabled.as_deref())).then_some("disabled"),
89
9
        (!script.has_source).then_some("no source"),
90
9
    ]
91
9
    .into_iter()
92
9
    .flatten()
93
9
    .collect();
94
9
    match states.is_empty() {
95
4
        true => label.to_string(),
96
5
        false => format!("{label} ({})", states.join(", ")),
97
    }
98
9
}
99

            
100
4
fn script_options(listed: Vec<ScriptInfo>) -> Vec<FormOption> {
101
4
    let names: Vec<(Uuid, Vec<String>)> = listed
102
4
        .iter()
103
9
        .map(|script| {
104
9
            let name = script.name.as_deref().unwrap_or("unnamed");
105
9
            (script.id, vec![name.to_string()])
106
9
        })
107
        .collect();
108
4
    let labels = unique_labels(&names, str::to_string);
109
4
    listed
110
4
        .into_iter()
111
4
        .zip(labels)
112
        .map(|(script, label)| FormOption {
113
9
            id: script.id,
114
9
            label: script_label(&label, &script),
115
9
            alias: label.clone(),
116
9
            path: label,
117
9
            commodity: None,
118
9
        })
119
        .collect()
120
4
}
121

            
122
1764
fn template_options(listed: Vec<TemplateInfo>) -> Vec<FormOption> {
123
1764
    let names: Vec<(Uuid, Vec<String>)> = listed
124
1764
        .iter()
125
1128
        .map(|template| {
126
1128
            let name = template.name.as_deref().unwrap_or("unnamed");
127
1128
            (template.id, vec![name.to_string()])
128
1128
        })
129
        .collect();
130
1764
    let labels = unique_labels(&names, str::to_string);
131
1764
    listed
132
1764
        .into_iter()
133
1764
        .zip(labels)
134
        .map(|(template, label)| FormOption {
135
1128
            id: template.id,
136
1128
            alias: label.clone(),
137
1128
            path: label.clone(),
138
1128
            label,
139
1128
            commodity: None,
140
1128
        })
141
        .collect()
142
1764
}