1
use forms::{ACCOUNT_EDIT, FormValues, Row};
2
use server::command::account::SetAccountTag;
3
use sqlx::PgPool;
4
use uuid::Uuid;
5

            
6
use super::test_seed::{seed_account, seed_child_account, seed_user};
7
use crate::forms::{Failure, load, submit};
8

            
9
34
pub(super) async fn loaded(user: Uuid, account: Uuid) -> anyhow::Result<FormValues> {
10
34
    Ok(load(user, &ACCOUNT_EDIT, &account.to_string()).await?)
11
34
}
12

            
13
60
pub(super) async fn set_tag(
14
60
    user: Uuid,
15
60
    account: Uuid,
16
60
    name: &str,
17
60
    value: &str,
18
60
) -> anyhow::Result<()> {
19
60
    SetAccountTag::new()
20
60
        .user_id(user)
21
60
        .account_id(account)
22
60
        .tag_name(name.to_string())
23
60
        .tag_value(value.to_string())
24
60
        .run()
25
60
        .await?;
26
60
    Ok(())
27
60
}
28

            
29
11
pub(super) fn tag_row(name: &str, value: &str) -> Row {
30
11
    Row::from([
31
11
        ("name".to_string(), name.to_string()),
32
11
        ("value".to_string(), value.to_string()),
33
11
    ])
34
11
}
35

            
36
6
pub(super) fn with_tags(values: &FormValues, rows: Vec<Row>) -> FormValues {
37
6
    let mut edited = values.clone();
38
6
    edited.set_rows("tags");
39
6
    for row in rows {
40
11
        edited.push_row("tags", row);
41
    }
42
6
    edited
43
6
}
44

            
45
/// The values with `tags` replaced by `rows`; `set_rows` keeps old rows, so
46
/// rebuild from the scalar fields.
47
6
pub(super) fn rebuilt(values: &FormValues, rows: Vec<Row>) -> FormValues {
48
6
    let mut edited = FormValues::default();
49
6
    for key in ["id", "revision", "name", "parent"] {
50
24
        edited.set(key, values.text(key).unwrap_or_default());
51
    }
52
6
    with_tags(&edited, rows)
53
6
}
54

            
55
14
pub(super) async fn invalid_fields(user: Uuid, values: &FormValues) -> anyhow::Result<Vec<String>> {
56
14
    match submit(user, &ACCOUNT_EDIT, values).await {
57
15
        Err(Failure::Invalid(errors)) => Ok(errors.into_iter().map(|e| e.field).collect()),
58
        other => anyhow::bail!("expected field errors, got {other:?}"),
59
    }
60
14
}
61

            
62
pub(super) struct Seeded {
63
    pub(super) user: Uuid,
64
    pub(super) parent: Uuid,
65
    pub(super) account: Uuid,
66
}
67

            
68
28
pub(super) async fn seeded(pool: &PgPool) -> anyhow::Result<Seeded> {
69
28
    let user = seed_user(pool).await?;
70
28
    let parent = seed_account(user, "Assets").await?;
71
28
    let account = seed_child_account(user, "Cash", parent).await?;
72
28
    set_tag(user, account, "type", "asset").await?;
73
28
    set_tag(user, account, "color", "red").await?;
74
28
    Ok(Seeded {
75
28
        user,
76
28
        parent,
77
28
        account,
78
28
    })
79
28
}