1
//! Pins the template prefill of the web create page (plan 0016): the template
2
//! wins over `from_account`, carries note, tags and an explicit date, and
3
//! refuses a malformed date or an unrepresentable pairing. Since W5 the page
4
//! is the shared-forms page and its prefill is `load-form
5
//! "transaction-create"`.
6

            
7
use axum::http::StatusCode;
8
use forms::Source;
9
use sqlx::types::Uuid;
10
use web::model::User;
11

            
12
use crate::common::new_page::{
13
    created_id, get_page, input_value, option_id, post_form, seeded_user, snapshot, textarea,
14
    without_entered,
15
};
16
use crate::common::seed::named_account;
17

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

            
26
10
async fn template(user: &User, source: &str) -> Uuid {
27
10
    server::user::User { id: user.id }
28
10
        .create_template(source.to_string(), Some("prefill".to_string()))
29
10
        .await
30
10
        .expect("create template")
31
10
}
32

            
33
#[supp_macro::shared_runtime_test]
34
1
async fn a_template_prefill_carries_note_tags_date_and_rows() {
35
1
    let user = seeded_user().await;
36
1
    let id = template(&user, GROCERIES).await;
37
1
    let checking = option_id(&user, Source::Accounts, "Assets:Checking").await;
38
1
    let food = option_id(&user, Source::Accounts, "Expenses:Food").await;
39

            
40
1
    let reply = get_page(&user, &format!("template={id}")).await;
41

            
42
1
    assert_eq!(reply.status, StatusCode::OK, "{}", reply.body);
43
1
    let html = &reply.body;
44
1
    assert_eq!(textarea(html, "note"), Some("Groceries"));
45
1
    assert_eq!(input_value(html, "date"), Some("2026-06-15T12:00:00Z"));
46
1
    assert_eq!(input_value(html, "tags.0.name"), Some("category"));
47
1
    assert_eq!(input_value(html, "tags.0.value"), Some("food"));
48
2
    let id_text = |id: Uuid| id.to_string();
49
1
    assert_eq!(
50
1
        input_value(html, "splits.0.from"),
51
1
        Some(id_text(checking).as_str())
52
    );
53
1
    assert_eq!(
54
1
        input_value(html, "splits.0.to"),
55
1
        Some(id_text(food).as_str())
56
    );
57
1
    assert_eq!(
58
1
        input_value(html, "label:splits.0.from"),
59
1
        Some("Assets:Checking")
60
    );
61
1
    assert_eq!(
62
1
        input_value(html, "label:splits.0.to"),
63
1
        Some("Expenses:Food")
64
    );
65
1
    assert_eq!(input_value(html, "splits.0.value"), Some("50"));
66
1
    assert_eq!(input_value(html, "splits.1.from"), None);
67
}
68

            
69
/// Flipped in W5: the server drops `from_account` when a template is given
70
/// (before, both were emitted and only the wasm picked the draft).
71
#[supp_macro::shared_runtime_test]
72
1
async fn a_template_wins_over_from_account() {
73
1
    let user = seeded_user().await;
74
1
    let id = template(&user, GROCERIES).await;
75
1
    let wallet = named_account(user.id, "Assets:Wallet").await;
76

            
77
1
    let reply = get_page(&user, &format!("from_account={wallet}&template={id}")).await;
78

            
79
1
    assert_eq!(reply.status, StatusCode::OK, "{}", reply.body);
80
1
    assert_eq!(textarea(&reply.body, "note"), Some("Groceries"));
81
1
    assert_eq!(
82
1
        input_value(&reply.body, "label:splits.0.from"),
83
1
        Some("Assets:Checking")
84
    );
85
1
    assert!(!reply.body.contains("Assets:Wallet"), "{}", reply.body);
86
1
    assert!(!reply.body.contains(&wallet.to_string()), "{}", reply.body);
87
}
88

            
89
#[supp_macro::shared_runtime_test]
90
1
async fn a_template_without_a_date_starts_now() {
91
1
    let user = seeded_user().await;
92
1
    let id = template(
93
1
        &user,
94
1
        &GROCERIES.replace("(set-draft-date \"2026-06-15\")", ""),
95
1
    )
96
1
    .await;
97

            
98
1
    let reply = get_page(&user, &format!("template={id}")).await;
99

            
100
1
    assert_eq!(reply.status, StatusCode::OK, "{}", reply.body);
101
1
    let date = input_value(&reply.body, "date").unwrap_or_default();
102
1
    assert!(chrono::DateTime::parse_from_rfc3339(date).is_ok(), "{date}");
103
1
    assert!(date.ends_with('Z'), "{date}");
104
}
105

            
106
/// The refusal of a page a browser navigated to is an HTML page in the
107
/// layout with a way back, never raw JSON.
108
#[supp_macro::shared_runtime_test]
109
1
async fn a_refused_template_is_an_html_page() {
110
1
    let user = seeded_user().await;
111
1
    let source = GROCERIES.replace("2026-06-15", "15th of June");
112
1
    let id = template(&user, &source).await;
113

            
114
1
    let reply = get_page(&user, &format!("template={id}")).await;
115

            
116
1
    assert_refused(reply.status, &reply.body);
117
1
    let content_type = reply.headers.get("content-type").expect("content type");
118
1
    assert!(
119
1
        content_type
120
1
            .to_str()
121
1
            .is_ok_and(|t| t.starts_with("text/html"))
122
    );
123
1
    assert!(
124
1
        reply.body.contains("<title>Error</title>"),
125
        "{}",
126
        reply.body
127
    );
128
1
    assert!(reply.body.contains(">Back</a>"), "{}", reply.body);
129
1
    assert!(!reply.body.contains("\"status\""), "{}", reply.body);
130
}
131

            
132
4
fn assert_refused(status: StatusCode, body: &str) {
133
4
    assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "{body}");
134
4
    assert!(body.contains("cannot be shown as a form"), "{body}");
135
4
    assert!(!body.contains("nf-transaction-create"), "{body}");
136
4
}
137

            
138
#[supp_macro::shared_runtime_test]
139
1
async fn a_template_with_a_malformed_date_is_refused() {
140
1
    let user = seeded_user().await;
141
1
    let source = GROCERIES.replace("2026-06-15", "15th of June");
142
1
    let id = template(&user, &source).await;
143

            
144
1
    let reply = get_page(&user, &format!("template={id}")).await;
145

            
146
1
    assert_refused(reply.status, &reply.body);
147
}
148

            
149
/// Flipped in W5: the `1/3` pairing is exact, so the shared loader shows it;
150
/// the legacy page refused it as non-terminating.
151
#[supp_macro::shared_runtime_test]
152
1
async fn a_template_with_fractions_prefills_them_exactly() {
153
1
    let user = seeded_user().await;
154
1
    let source = GROCERIES
155
1
        .replace("-50/1)", "-1/3)")
156
1
        .replace(" 50/1)", " 1/3)");
157
1
    let id = template(&user, &source).await;
158

            
159
1
    let reply = get_page(&user, &format!("template={id}")).await;
160

            
161
1
    assert_eq!(reply.status, StatusCode::OK, "{}", reply.body);
162
1
    assert_eq!(input_value(&reply.body, "splits.0.value"), Some("1/3"));
163
}
164

            
165
#[supp_macro::shared_runtime_test]
166
1
async fn a_template_with_an_unpaired_leg_is_refused() {
167
1
    let user = seeded_user().await;
168
1
    let unpaired = format!(
169
1
        "{GROCERIES}(draft-split (get-account \"Expenses:Food\") (get-commodity \"USD\") 1/1)"
170
    );
171
1
    let id = template(&user, &unpaired).await;
172

            
173
1
    let reply = get_page(&user, &format!("template={id}")).await;
174

            
175
1
    assert_refused(reply.status, &reply.body);
176
}
177

            
178
#[supp_macro::shared_runtime_test]
179
1
async fn a_failing_template_shows_the_authors_error() {
180
1
    let user = seeded_user().await;
181
1
    let id = template(&user, "(error 'my-code \"boom\")").await;
182

            
183
1
    let reply = get_page(&user, &format!("template={id}")).await;
184

            
185
1
    assert_refused(reply.status, &reply.body);
186
1
    assert!(reply.body.contains("boom"), "{}", reply.body);
187
}
188

            
189
#[supp_macro::shared_runtime_test]
190
1
async fn a_missing_template_is_a_404() {
191
1
    let user = seeded_user().await;
192
1
    let reply = get_page(&user, &format!("template={}", Uuid::new_v4())).await;
193

            
194
1
    assert_eq!(reply.status, StatusCode::NOT_FOUND, "{}", reply.body);
195
1
    assert!(
196
1
        !reply.body.contains("nf-transaction-create"),
197
        "{}",
198
        reply.body
199
    );
200
}
201

            
202
#[supp_macro::shared_runtime_test]
203
1
async fn a_same_currency_template_leaves_the_to_commodity_empty() {
204
1
    let user = seeded_user().await;
205
1
    let id = template(&user, GROCERIES).await;
206

            
207
1
    let reply = get_page(&user, &format!("template={id}")).await;
208

            
209
1
    assert_eq!(reply.status, StatusCode::OK, "{}", reply.body);
210
1
    let html = &reply.body;
211
1
    assert_eq!(input_value(html, "splits.0.to-commodity"), Some(""));
212
1
    assert_eq!(input_value(html, "label:splits.0.to-commodity"), Some(""));
213
1
    assert_eq!(
214
1
        input_value(html, "label:splits.0.from-commodity"),
215
1
        Some("USD")
216
    );
217
}
218

            
219
const PREFILLED: [&str; 12] = [
220
    "date",
221
    "tags.0.name",
222
    "tags.0.value",
223
    "splits.0.key",
224
    "splits.0.from",
225
    "splits.0.to",
226
    "splits.0.from-commodity",
227
    "splits.0.to-commodity",
228
    "label:splits.0.from-commodity",
229
    "label:splits.0.to-commodity",
230
    "splits.0.value",
231
    "splits.0.to-amount",
232
];
233

            
234
1
fn prefilled(html: &str) -> Vec<(&'static str, &str)> {
235
1
    let mut pairs = vec![
236
1
        ("note", textarea(html, "note").unwrap_or_default()),
237
1
        ("tags", ""),
238
1
        ("splits", ""),
239
1
        ("splits.0.hidden", ""),
240
1
        ("split-tags", ""),
241
    ];
242
12
    pairs.extend(PREFILLED.map(|name| (name, input_value(html, name).unwrap_or_default())));
243
1
    pairs
244
1
}
245

            
246
/// The prefilled same-currency row, its to-commodity empty, submits as the
247
/// plain one-commodity entry with no conversion price.
248
#[supp_macro::shared_runtime_test]
249
1
async fn a_prefilled_same_currency_template_submits_without_a_price() {
250
1
    let user = seeded_user().await;
251
1
    let id = template(&user, GROCERIES).await;
252
1
    let page = get_page(&user, &format!("template={id}")).await;
253
1
    let pairs = prefilled(&page.body);
254
1
    let plain: Vec<_> = pairs
255
1
        .iter()
256
1
        .copied()
257
17
        .filter(|(name, _)| !name.ends_with("to-commodity"))
258
        .collect();
259

            
260
1
    let posted = post_form(&user, &pairs).await;
261
1
    let baseline = post_form(&user, &plain).await;
262
1
    let facts = snapshot(&user, created_id(&posted)).await;
263
1
    let before = snapshot(&user, created_id(&baseline)).await;
264

            
265
1
    assert_eq!(page.status, StatusCode::OK, "{}", page.body);
266
1
    assert!(pairs.contains(&("splits.0.to-commodity", "")), "{pairs:?}");
267
1
    assert_eq!(posted.status, StatusCode::OK, "{}", posted.body);
268
5
    assert!(facts.iter().all(|f| !f.starts_with("price ")), "{facts:?}");
269
1
    assert_eq!(without_entered(facts), without_entered(before));
270
}