1
//! The duplicate-name notice of account create and rename: a warning, never
2
//! a refusal.
3

            
4
use crate::command::connection;
5
use sqlx::types::Uuid;
6
use supp_macro::command;
7

            
8
use super::{CmdError, CmdResult};
9
use crate::user::User;
10

            
11
/// The one text every client shows when an account shares its name with a
12
/// sibling.
13
#[must_use]
14
3966
pub fn duplicate_name_notice(name: &str) -> String {
15
3966
    format!("Another account named '{name}' already exists under the same parent")
16
3966
}
17

            
18
command! {
19
    AccountNameNotice {
20
        #[required]
21
        user_id: Uuid,
22
        #[required]
23
        account_id: Uuid,
24
    } => {
25
        let user = User { id: user_id };
26
        let mut conn = connection(&user).await?;
27
        let row = sqlx::query_file!("sql/select/accounts/name_twins.sql", account_id)
28
            .fetch_optional(&mut *conn)
29
            .await?;
30
        Ok(row
31
17645
            .filter(|row| row.twins.unwrap_or_default() > 0)
32
2343
            .map(|row| CmdResult::String(duplicate_name_notice(&row.account_name))))
33
    }
34
70584
}
35

            
36
/// The notice for `account_id` after a create or rename, if it has a twin.
37
///
38
/// # Errors
39
/// The command's database error.
40
17646
pub async fn account_name_notice(
41
17646
    user_id: Uuid,
42
17646
    account_id: Uuid,
43
17646
) -> Result<Option<String>, CmdError> {
44
17646
    match AccountNameNotice::new()
45
17646
        .user_id(user_id)
46
17646
        .account_id(account_id)
47
17646
        .run()
48
17646
        .await?
49
    {
50
2343
        Some(CmdResult::String(notice)) => Ok(Some(notice)),
51
15303
        _ => Ok(None),
52
    }
53
17646
}