1
use forms::{FormValues, TEMPLATE_TEST, escape_str};
2
use sqlx::PgPool;
3

            
4
use super::test_edit::{Fx, fx};
5
use crate::ScriptCtx;
6
use crate::forms::{Failure, TemplateDraft, test_template};
7
use crate::session::Session;
8

            
9
const GROCERIES: &str = "(set-draft-note \"Groceries\")(set-draft-date \"2026-06-15\")\
10
    (draft-tag \"category\" \"food\")";
11

            
12
5
fn source_of(source: &str) -> FormValues {
13
5
    let mut values = FormValues::default();
14
5
    values.set("source", source);
15
5
    values
16
5
}
17

            
18
3
fn pair(fx: &Fx, value: &str) -> String {
19
3
    format!(
20
3
        "(draft-split (get-account \"Cash\") (get-commodity \"USD\") -{value})\
21
         (draft-split (get-account \"Food\") (get-commodity \"USD\") {value})\
22
         (draft-split-tag 0 \"memo\" \"{}\")",
23
3
        fx.usd
24
    )
25
3
}
26

            
27
2
async fn tested(fx: &Fx, source: &str) -> anyhow::Result<TemplateDraft> {
28
2
    Ok(test_template(fx.user, &source_of(source)).await?)
29
2
}
30

            
31
3
async fn field_error(fx: &Fx, source: &str) -> anyhow::Result<(String, String)> {
32
3
    match test_template(fx.user, &source_of(source)).await {
33
3
        Err(Failure::Invalid(mut errors)) if errors.len() == 1 => {
34
3
            let error = errors.remove(0);
35
3
            Ok((error.field, error.message))
36
        }
37
        other => anyhow::bail!("expected one field error, got {other:?}"),
38
    }
39
3
}
40

            
41
#[sqlx::test(migrator = "server::db::MIGRATOR")]
42
async fn a_good_template_returns_its_draft(pool: PgPool) -> anyhow::Result<()> {
43
    let _guard = server::db::install_test_pool(pool.clone());
44
    let fx = fx(&pool).await?;
45

            
46
    let drafted = tested(&fx, &format!("{GROCERIES}{}", pair(&fx, "1/3"))).await?;
47

            
48
    assert_eq!(drafted.refusal, None);
49
    assert_eq!(drafted.draft.note.as_deref(), Some("Groceries"));
50
    assert_eq!(drafted.draft.date.as_deref(), Some("2026-06-15"));
51
    assert_eq!(drafted.draft.tags.len(), 1);
52
    let accounts: Vec<&str> = drafted
53
        .draft
54
        .splits
55
        .iter()
56
2
        .map(|split| split.account_id.as_str())
57
        .collect();
58
    assert_eq!(accounts, [fx.cash.to_string(), fx.food.to_string()]);
59
    assert_eq!(drafted.draft.splits[0].tags.len(), 1);
60
    Ok(())
61
}
62

            
63
#[sqlx::test(migrator = "server::db::MIGRATOR")]
64
async fn a_draft_the_form_cannot_show_says_why(pool: PgPool) -> anyhow::Result<()> {
65
    let _guard = server::db::install_test_pool(pool.clone());
66
    let fx = fx(&pool).await?;
67
    let source = format!(
68
        "{GROCERIES}{}(draft-split (get-account \"Food\") (get-commodity \"USD\") 1/1)",
69
        pair(&fx, "5/1")
70
    );
71

            
72
    let drafted = tested(&fx, &source).await?;
73

            
74
    assert_eq!(
75
        drafted.refusal.as_deref(),
76
        Some("it has an odd number of splits")
77
    );
78
    assert_eq!(drafted.draft.splits.len(), 3);
79
    Ok(())
80
}
81

            
82
#[sqlx::test(migrator = "server::db::MIGRATOR")]
83
async fn a_compile_error_is_a_field_error_at_source(pool: PgPool) -> anyhow::Result<()> {
84
    let _guard = server::db::install_test_pool(pool.clone());
85
    let fx = fx(&pool).await?;
86

            
87
    let (field, message) = field_error(&fx, "(unclosed").await?;
88

            
89
    assert_eq!(field, "source");
90
    assert!(message.starts_with("template compile error: "), "{message}");
91
    Ok(())
92
}
93

            
94
#[sqlx::test(migrator = "server::db::MIGRATOR")]
95
async fn a_render_error_is_a_field_error_at_source(pool: PgPool) -> anyhow::Result<()> {
96
    let _guard = server::db::install_test_pool(pool.clone());
97
    let fx = fx(&pool).await?;
98

            
99
    let (field, message) = field_error(&fx, "(error 'my-code \"boom\")").await?;
100

            
101
    assert_eq!(field, "source");
102
    assert_eq!(message, "template render error: MY-CODE: boom");
103
    Ok(())
104
}
105

            
106
#[sqlx::test(migrator = "server::db::MIGRATOR")]
107
async fn an_empty_source_is_a_required_field(pool: PgPool) -> anyhow::Result<()> {
108
    let _guard = server::db::install_test_pool(pool.clone());
109
    let fx = fx(&pool).await?;
110

            
111
    let (field, _) = field_error(&fx, "  ").await?;
112

            
113
    assert_eq!(field, "source");
114
    Ok(())
115
}
116

            
117
#[sqlx::test(migrator = "server::db::MIGRATOR")]
118
async fn the_draft_prints_as_a_keyword_plist(pool: PgPool) -> anyhow::Result<()> {
119
    let _guard = server::db::install_test_pool(pool.clone());
120
    let fx = fx(&pool).await?;
121
    let mut session = Session::new(ScriptCtx::new(fx.user))?;
122
    let source = format!("{GROCERIES}{}", pair(&fx, "1/3"));
123
    let payload = format!("(:source {})", escape_str(&source));
124
    let form = format!(
125
        "(submit-form {} {})",
126
        escape_str(TEMPLATE_TEST.name),
127
        escape_str(&payload)
128
    );
129

            
130
    let wire = session.handle_form(&format!("(:id 1 :form {form})")).await;
131

            
132
    let (cash, food, usd) = (fx.cash, fx.food, fx.usd);
133
    let expected = format!(
134
        "(:id 1 :value (:NOTE \"Groceries\" :DATE \"2026-06-15\" :SPLITS \
135
         ((:ACCOUNT \"{cash}\" :AMOUNT \"-1/3\" :COMMODITY \"{usd}\" :TAGS ((:NAME \"memo\" :VALUE \"{usd}\"))) \
136
         (:ACCOUNT \"{food}\" :AMOUNT \"1/3\" :COMMODITY \"{usd}\" :TAGS nil)) \
137
         :TAGS ((:NAME \"category\" :VALUE \"food\")) :PREFILLABLE t :REASON nil))"
138
    );
139
    assert_eq!(wire, expected);
140
    Ok(())
141
}