1
//! The `convert` query form: an amount between two commodities over the Prices table.
2

            
3
use forms::{CONVERT, FieldError, FormValues};
4
use num_rational::Rational64;
5
use server::command::commodity::ConvertCommodity;
6
use server::command::{CmdError, CmdResult};
7
use uuid::Uuid;
8

            
9
use super::Failure;
10
use super::query::{field_error, filled};
11
use crate::resolve::Directory;
12
use crate::resolve::options::DirectorySource;
13

            
14
const CTX: &str = "convert";
15

            
16
struct Request {
17
    amount: (i64, i64),
18
    from: Uuid,
19
    to: Uuid,
20
}
21

            
22
1936
fn commodity(
23
1936
    directory: &Directory,
24
1936
    values: &FormValues,
25
1936
    key: &str,
26
1936
    errors: &mut Vec<FieldError>,
27
1936
) -> Option<Uuid> {
28
1936
    let text = filled(values, key)?;
29
1935
    directory
30
1935
        .own_commodity(text)
31
1
        .map_err(|fault| errors.push(field_error(key, fault.to_string())))
32
        .ok()
33
1936
}
34

            
35
968
async fn request(user_id: Uuid, values: &FormValues) -> Result<Request, Failure> {
36
968
    let mut errors = values.check(&CONVERT);
37
968
    let directory = Directory::load(CTX, user_id).await?;
38
968
    let from = commodity(&directory, values, "from", &mut errors);
39
968
    let to = commodity(&directory, values, "to", &mut errors);
40
968
    if from.is_some() && from == to {
41
161
        errors.push(field_error("to", "must differ from the source commodity"));
42
807
    }
43
968
    let amount = filled(values, "amount").and_then(|text| amount::parse_amount(text).ok());
44
968
    match (errors.is_empty(), amount, from, to) {
45
646
        (true, Some(amount), Some(from), Some(to)) => Ok(Request { amount, from, to }),
46
322
        _ => Err(errors.into()),
47
    }
48
968
}
49

            
50
642
fn symbol(directory: &Directory, id: Uuid) -> String {
51
642
    directory
52
642
        .options(DirectorySource::Commodities)
53
642
        .into_iter()
54
963
        .find(|option| option.id == id)
55
642
        .map_or_else(|| id.to_string(), |option| option.alias)
56
642
}
57

            
58
322
async fn failure(user_id: Uuid, request: &Request, err: CmdError) -> Failure {
59
322
    match err {
60
        CmdError::NoPrice { .. } => {
61
321
            let named = Directory::load(CTX, user_id).await.map(|directory| {
62
321
                let from = symbol(&directory, request.from);
63
321
                let to = symbol(&directory, request.to);
64
321
                format!("no exchange rate between {from} and {to}")
65
321
            });
66
321
            named.map_or_else(Failure::from, Failure::Refused)
67
        }
68
1
        other => Failure::from_command(CTX, other),
69
    }
70
322
}
71

            
72
/// `convert` query: the amount in the target commodity.
73
968
pub async fn convert(user_id: Uuid, values: &FormValues) -> Result<Rational64, Failure> {
74
968
    let request = request(user_id, values).await?;
75
646
    let converted = ConvertCommodity::new()
76
646
        .user_id(user_id)
77
646
        .amount_num(request.amount.0)
78
646
        .amount_denom(request.amount.1)
79
646
        .source_commodity_id(request.from)
80
646
        .target_commodity_id(request.to)
81
646
        .run()
82
646
        .await;
83
646
    match converted {
84
324
        Ok(Some(CmdResult::Rational(ratio))) => Ok(ratio),
85
        Ok(other) => Err(Failure::Internal(wasmtime::Error::msg(format!(
86
            "{CTX}: unexpected result {other:?}"
87
        )))),
88
322
        Err(err) => Err(failure(user_id, &request, err).await),
89
    }
90
968
}