1
//! The template test answers from the `template-test` query form, and its
2
//! verdict agrees with the loader of `transaction-create`.
3

            
4
use axum::{Router, http::StatusCode, routing::post};
5
use web::model::User;
6
use web::pages::template::draft::{TEST_PATH, template_test};
7

            
8
use crate::common::create_mock_user;
9
use crate::common::entity_edit::{get_from, post_to};
10
use crate::common::new_page::Reply;
11
use crate::common::seed::{named_account, named_commodity};
12
use crate::common::tenant::provision_tenant;
13

            
14
const GROCERIES: &str = r#"
15
    (set-draft-note "Groceries")
16
    (set-draft-date "2026-06-15")
17
    (draft-tag "category" "food")
18
    (draft-split (get-account "Assets:Checking") (get-commodity "USD") -50/1)
19
    (draft-split (get-account "Expenses:Food") (get-commodity "USD") 50/1)
20
"#;
21

            
22
const EXTRA_LEG: &str = r#"(draft-split (get-account "Expenses:Food") (get-commodity "USD") 1/1)"#;
23

            
24
2
fn tagged_legs(first: &str, second: &str) -> String {
25
2
    format!(
26
2
        "{GROCERIES}(draft-split-tag 0 \"memo\" \"{first}\")(draft-split-tag 1 \"memo\" \"{second}\")"
27
    )
28
2
}
29

            
30
8
async fn seeded_user() -> User {
31
8
    let user = create_mock_user();
32
8
    provision_tenant(user.id).await;
33
8
    named_commodity(user.id, "USD").await;
34
8
    named_account(user.id, "Assets:Checking").await;
35
8
    named_account(user.id, "Expenses:Food").await;
36
8
    user
37
8
}
38

            
39
15
fn router() -> Router<std::sync::Arc<web::AppState>> {
40
15
    Router::new().route(TEST_PATH, post(template_test))
41
15
}
42

            
43
14
async fn test_source(user: &User, source: &str) -> Reply {
44
14
    let pairs = [("source".to_string(), source.to_string())];
45
14
    post_to(router(), user, TEST_PATH, &pairs).await
46
14
}
47

            
48
6
async fn loads(user: &User, source: &str) -> bool {
49
6
    let id = server::user::User { id: user.id }
50
6
        .create_template(source.to_string(), None)
51
6
        .await
52
6
        .expect("create template");
53
6
    rpc::forms::load(user.id, &forms::TRANSACTION_CREATE, &id.to_string())
54
6
        .await
55
        .is_ok()
56
6
}
57

            
58
#[supp_macro::shared_runtime_test]
59
1
async fn a_good_template_shows_its_draft_with_labels() {
60
1
    let user = seeded_user().await;
61
1
    let reply = test_source(&user, GROCERIES).await;
62

            
63
1
    assert_eq!(reply.status, StatusCode::OK, "{}", reply.body);
64
1
    for shown in [
65
1
        "Groceries",
66
1
        "2026-06-15",
67
1
        "Assets:Checking",
68
1
        "Expenses:Food",
69
1
        "USD",
70
1
        "-50",
71
1
        "category=food",
72
1
        "Ready to pre-fill",
73
1
    ] {
74
8
        assert!(reply.body.contains(shown), "{shown}: {}", reply.body);
75
    }
76
}
77

            
78
#[supp_macro::shared_runtime_test]
79
1
async fn a_draft_that_cannot_prefill_names_the_reason() {
80
1
    let user = seeded_user().await;
81
1
    let reply = test_source(&user, &format!("{GROCERIES}{EXTRA_LEG}")).await;
82

            
83
1
    assert_eq!(reply.status, StatusCode::OK, "{}", reply.body);
84
1
    assert!(reply.body.contains("can't pre-fill"), "{}", reply.body);
85
1
    assert!(
86
1
        reply.body.contains("odd number of splits"),
87
        "{}",
88
        reply.body
89
    );
90
}
91

            
92
#[supp_macro::shared_runtime_test]
93
1
async fn a_compile_error_is_a_422_at_the_source() {
94
1
    let user = seeded_user().await;
95
1
    let reply = test_source(&user, "(unclosed").await;
96

            
97
1
    assert_eq!(
98
1
        reply.status,
99
1
        StatusCode::UNPROCESSABLE_ENTITY,
100
        "{}",
101
        reply.body
102
    );
103
1
    assert_eq!(
104
1
        reply
105
1
            .headers
106
1
            .get("hx-retarget")
107
1
            .and_then(|v| v.to_str().ok()),
108
1
        Some("#template-test-result")
109
    );
110
1
    assert!(
111
1
        reply.body.contains("data-field=\"source\""),
112
        "{}",
113
        reply.body
114
    );
115
}
116

            
117
#[supp_macro::shared_runtime_test]
118
1
async fn a_render_error_is_a_422_at_the_source() {
119
1
    let user = seeded_user().await;
120
1
    let reply = test_source(&user, "(error 'my-code \"boom\")").await;
121

            
122
1
    assert_eq!(
123
1
        reply.status,
124
1
        StatusCode::UNPROCESSABLE_ENTITY,
125
        "{}",
126
        reply.body
127
    );
128
1
    assert!(
129
1
        reply.body.contains("data-field=\"source\""),
130
        "{}",
131
        reply.body
132
    );
133
1
    assert!(reply.body.contains("boom"), "{}", reply.body);
134
}
135

            
136
#[supp_macro::shared_runtime_test]
137
1
async fn an_empty_source_is_a_422_at_the_source() {
138
1
    let user = seeded_user().await;
139
1
    let reply = test_source(&user, "").await;
140

            
141
1
    assert_eq!(
142
1
        reply.status,
143
1
        StatusCode::UNPROCESSABLE_ENTITY,
144
        "{}",
145
        reply.body
146
    );
147
1
    assert!(
148
1
        reply.body.contains("data-field=\"source\""),
149
        "{}",
150
        reply.body
151
    );
152
}
153

            
154
#[supp_macro::shared_runtime_test]
155
1
async fn an_unreachable_tenant_is_a_503() {
156
1
    let user = create_mock_user();
157
1
    let reply = test_source(&user, "(get-commodity \"USD\")").await;
158

            
159
1
    assert_eq!(
160
1
        reply.status,
161
1
        StatusCode::SERVICE_UNAVAILABLE,
162
        "{}",
163
        reply.body
164
    );
165
}
166

            
167
#[supp_macro::shared_runtime_test]
168
1
async fn the_test_agrees_with_the_loader() {
169
1
    let user = seeded_user().await;
170
1
    let fraction = GROCERIES
171
1
        .replace("-50/1)", "-1/3)")
172
1
        .replace(" 50/1)", " 1/3)");
173
1
    let cases = [
174
1
        (GROCERIES.to_string(), true),
175
1
        (fraction, true),
176
1
        (GROCERIES.replace("2026-06-15", "15th of June"), false),
177
1
        (format!("{GROCERIES}{EXTRA_LEG}"), false),
178
1
        (tagged_legs("a", "b"), true),
179
1
        (tagged_legs("a", "a"), true),
180
1
    ];
181

            
182
1
    for (source, expected) in cases {
183
6
        let reply = test_source(&user, &source).await;
184
6
        assert_eq!(reply.status, StatusCode::OK, "{source}: {}", reply.body);
185
6
        assert_eq!(
186
6
            reply.body.contains("Ready to pre-fill"),
187
6
            expected,
188
            "{source}: {}",
189
            reply.body
190
        );
191
6
        assert_eq!(loads(&user, &source).await, expected, "{source}");
192
    }
193
}
194

            
195
#[supp_macro::shared_runtime_test]
196
1
async fn the_source_travels_in_the_body_not_the_url() {
197
1
    let user = seeded_user().await;
198
1
    let query = serde_urlencoded::to_string([("source", GROCERIES)]).expect("query");
199
1
    let by_get = get_from(router(), &user, &format!("{TEST_PATH}?{query}")).await;
200

            
201
1
    assert_eq!(
202
1
        by_get.status,
203
1
        StatusCode::METHOD_NOT_ALLOWED,
204
        "{}",
205
        by_get.body
206
    );
207
1
    assert_eq!(test_source(&user, GROCERIES).await.status, StatusCode::OK);
208
}
209

            
210
#[supp_macro::shared_runtime_test]
211
1
async fn a_source_longer_than_8_kb_is_tested() {
212
1
    let user = seeded_user().await;
213
1
    let padding = "; padding padding padding padding\n".repeat(400);
214
1
    let source = format!("{GROCERIES}{padding}");
215
1
    assert!(source.len() > 8 * 1024);
216

            
217
1
    let reply = test_source(&user, &source).await;
218

            
219
1
    assert_eq!(reply.status, StatusCode::OK, "{}", reply.body);
220
1
    assert!(reply.body.contains("Ready to pre-fill"), "{}", reply.body);
221
}