1
//! The free-text suggestions of a text cell, shared by every client.
2

            
3
use forms::{Scope, Suggest};
4
use server::error::ServerError;
5
use server::user::User;
6
use uuid::Uuid;
7

            
8
/// What a text cell asks to be suggested.
9
#[derive(Debug, Clone, PartialEq, Eq)]
10
pub enum Suggestion {
11
    TagNames(Scope),
12
    /// The values of the tag of this scope with this name.
13
    TagValues(Scope, String),
14
}
15

            
16
impl Suggestion {
17
    /// The request `suggest` makes; a values source needs the tag name and a
18
    /// names source takes none.
19
    ///
20
    /// # Errors
21
    /// The message naming the misplaced or missing tag name.
22
3068
    pub fn of(suggest: Suggest, tag: Option<&str>) -> Result<Self, String> {
23
3068
        match (suggest, tag) {
24
1446
            (Suggest::TagNames(scope), None) => Ok(Self::TagNames(scope)),
25
1140
            (Suggest::TagValues(scope), Some(tag)) => Ok(Self::TagValues(scope, tag.to_string())),
26
481
            (Suggest::TagNames(_), Some(_)) => Err(format!("{} takes no tag name", suggest.name())),
27
            (Suggest::TagValues(_), None) => {
28
1
                Err(format!("{0} needs '{0}:<tag name>'", suggest.name()))
29
            }
30
        }
31
3068
    }
32
}
33

            
34
/// The user's strings for `request`.
35
///
36
/// # Errors
37
/// The server's failure to list them.
38
2586
pub async fn suggestions(user_id: Uuid, request: &Suggestion) -> Result<Vec<String>, ServerError> {
39
2586
    let user = User { id: user_id };
40
2586
    match request {
41
481
        Suggestion::TagNames(Scope::Transaction) => user.list_transaction_tag_names().await,
42
643
        Suggestion::TagNames(Scope::Split) => user.list_split_tag_names().await,
43
321
        Suggestion::TagNames(Scope::Account) => user.list_account_tag_names().await,
44
321
        Suggestion::TagNames(Scope::Commodity) => user.list_commodity_tag_names().await,
45
        Suggestion::TagValues(Scope::Transaction, tag) => {
46
164
            user.list_transaction_tag_values(tag).await
47
        }
48
328
        Suggestion::TagValues(Scope::Split, tag) => user.list_split_tag_values(tag).await,
49
164
        Suggestion::TagValues(Scope::Account, tag) => user.list_account_tag_values(tag).await,
50
164
        Suggestion::TagValues(Scope::Commodity, tag) => user.list_commodity_tag_values(tag).await,
51
    }
52
2586
}