1
//! The `commodity-create` form submit: a symbol and a name.
2

            
3
use forms::{COMMODITY_CREATE, FormValues};
4
use server::command::CmdResult;
5
use server::command::commodity::CreateCommodity;
6
use uuid::Uuid;
7

            
8
use super::Failure;
9
use super::transaction_rows::single_line;
10

            
11
const CTX: &str = "commodity-create";
12

            
13
fn internal(message: String) -> Failure {
14
    Failure::Internal(wasmtime::Error::msg(format!("{CTX}: {message}")))
15
}
16

            
17
/// `commodity-create` submit: the new commodity's id.
18
1289
pub(super) async fn create_commodity(user_id: Uuid, values: &FormValues) -> Result<Uuid, Failure> {
19
1289
    let mut errors = values.check(&COMMODITY_CREATE);
20
1289
    for key in ["symbol", "name"] {
21
2578
        let text = values.text(key).unwrap_or_default().trim();
22
2578
        errors.extend(single_line(key, text).err());
23
    }
24
1289
    if !errors.is_empty() {
25
327
        return Err(errors.into());
26
962
    }
27
962
    let symbol = values.text("symbol").unwrap_or_default().trim().to_string();
28
962
    let name = values.text("name").unwrap_or_default().trim().to_string();
29
962
    let created = CreateCommodity::new()
30
962
        .symbol(symbol)
31
962
        .name(name)
32
962
        .user_id(user_id)
33
962
        .run()
34
962
        .await
35
320
        .map_err(|err| Failure::from_command(CTX, err))?;
36
642
    match created {
37
        Some(CmdResult::String(id)) => {
38
642
            Uuid::parse_str(&id).map_err(|err| internal(err.to_string()))
39
        }
40
        other => Err(internal(format!("unexpected create result {other:?}"))),
41
    }
42
1289
}